python(一):构造方法 /类的初始化
init
当类中的一个对象被创建时,会立即调用构造方法。
构造方法
init
的使用:
class FooBar:
def __init__(self):
self.somevar = 42
f = FooBar()
print f.somevar
(这里注意f = FooBar(),要带括号)
输出结果:
42
- 带参数构造
class FooBar:
def __init__(self,value=42):
self.somevar = value
f = FooBar("this is a constructor argument")
print f.somevar
输出结果:
this is a constructor argument
重写构造方法
子类中如果重写了构造方法, 那么就自动覆盖掉了父类构造方法了,那么如果只是想在子类构造方法中增加一些内容,如何做到只是增加内容而不覆盖父类中原有的内容呢?有两种方法:
-
调用未绑定的超类构造方法
首先看一个例子:
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print "Aaaah"
self.hungry = False
else:
print "No,thanks"
定义了一个父类 Bird。下面定义一个子类:
class SingBird:
def __init__(self):
Bird.__init__(self)
self.sound = "squawk"
def sing(self):
print self.sound
这里使用了
Bird.
init
(self)
这样就可以在父类的基础上增加内容了。
2. 使用super函数
class SingBird:
def __init__(self):
super(SingBird,self).__init__()
self.sound = "squawk"
def sing(self):
print self.sound
使用
super(SingBird,self).
init
()
版权声明:本文为yeizisn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。