您的位置:首页 > 编程语言 > Python开发

python构造方法学习笔记(一)

2014-11-27 00:00 344 查看
摘要: 类的构造方法

#!/usr/bin/python
class A:
def hello(self):
print 'hello A'
class B(A):
def hello(self):
print 'hello B'

b=B()
b.hello()

为了确保类是新型的,应该把赋值语句__metaclass__ = type放在模块的最开始。

构造方法:

每个类都可能拥有一个或者多个超类,它们从超类那里继承行为方式。如果一个方法在B类的一个实例中被调用(或一个属性被访问),但在B类中没有找到该方法,那么就会去它的超类A里面找。因为B类没有定义自己的hello方法,所以当hello被调用时,会去超类A里面寻找。

#!/usr/bin/python
__metaclass__ = type
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print 'aaaaa'
self.hungry = False
else:
print 'no,3q'

class SongBird(Bird):
def __init__(self):
#        super(SongBird,self).__init__()
self.sound = 'squawk'
def sing(self):
print self.sound
sb=SongBird()
sb.sing()
sb.eat()
sb.eat()

运行:
squawk
Traceback (most recent call last):
File "class1_test.py", line 21, in <module>
sb.eat()
File "class1_test.py", line 7, in eat
if self.hungry:
AttributeError: 'SongBird' object has no attribute 'hungry'

构造方法用来初始化新创建对象的状态,大多数子类不仅要拥有自己的初始化代码,还要拥有超类的初始化代码。SongBird是Bird的一个子类,它继承了eat方法。在SongBird中,构造方法被重写,但是新的构造方法没有hungry属性。理论上SongBird的构造方法必须调用其超类Bird的构造方法来对其初始化。有两种方法:调用超类构造方法的未绑定版本,使用super函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: