所谓内部类,就是在类的内部定义的类,主要目的是为了更好的抽象现实世界
内部类的实例化方法
方法1:直接使用外部类调用内部类
object_name=putclass_name.inclass_name()
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" jack=People.Chinese() print jack.name
方法2:先对外部类进行实例化,然后在实例化内部类
out_name=outclass_name()
in_name=out_name.inclass_name()
in_name.method()
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" ren=People() jack=ren.Chinese() print jack.name3.通过类名来访问属性
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" print People.Chinese.name通过类访问属性name
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" print People.Chinese().name通过对象来访问属性name
魔术方法
1.__str__(self)
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" def __str__(self): return "this is people class" ren=People() print ren
构造函数与析构函数
构造函数:用于初始化类的内部状态,python 提供的构造函数是__init__():
__init__()方法是可选的,如果不提供,Python会给出一个默认的__init__方法
把类进行实例化的时候自动执行__init__()函数
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" def __str__(self): return "this is people class" def __init__(self): self.color='black' ren=People() print ren.color print People.color
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" def __str__(self): return "this is people class" def __init__(self,c='whilte'): self.color=c ren=People() print ren.color print People.color
class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" def __str__(self): return "this is people class" def __init__(self,c='whilte'): self.color=c jack=People('green') print jack.color print People.color根据对象访问的值是会变的,而根据类访问的属性是不会变的。
析构函数:用于释放对象占用的资源,Python提供的析构函数是__del__();
__del__()也是可选的,如果不提供,则python 会在后台提供默认析构函数
import gc class People(object): color='yellow' __age=30 class Chinese(object): #print "i an chiese" name="i am chinese" def __str__(self): return "this is people class" def __init__(self,c='whilte'): print "init**********" self.color=c self.think() def think(self): self.color='black' print "i am a %s" % self.color print "i am a thinker" print self.__age def __del__(self): print "delete********" # self.fd.close() print gc.collect() jack=People('green') print jack.color print People.color print "main end"