【学习整理】第九章节 魔法方法,属性和迭代器

一、构造器
1、无参数构造
class FooBar:
def __init__(self): # 构造函数前后两个下划线
self.somevar = 42
2、代参构造:
class FooBar:
def __init__(self,value=42): #这个参数是默认值,不传值默认为42 传值就会被覆盖
self.somevar = value
创建对象的时候这样使用:
f=FooBar('this is a constructor argument')
f.somevar
'this is a constructor argument '
 
3、与构造方法相对应的一个析构方法 是该对象被垃圾回收之前调用的方法
由于调用该方法的具体时间不可知,所以该方法慎用;
二、调用父类的构造方法
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
pritnt 'Aaaaah....'
self.hungry = False
else:
print 'No,thanks'
class SongBird(Brid):
def __init__(self):
#Brid.__init__(self) 方式一:老式的调用父类的方法
super(SongBird,self).__init__() #方式二:通过这种方式调用父类的构造方法
self.sound = "Squawk"
def sing(self):
print self.sound
 
原文地址:https://www.cnblogs.com/xujie09/p/7138167.html