-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
构造函数
-
在Python3中将不会存在旧式类,所有的类都将隐式地继承object.
-
__init__是Python中的构造函数,它将会在函数创建后被自动调用.
class Test:
def __init__(self, value=42):
print('12345',value)
t = Test('kkk') #输出12345 kkk
- 析构函数(destructor)的方法在Python中也被提供了,这个方法可以在对象被销毁前调用,但需要准确的知道调用时间,否则容易引起错误.
class Test:
def __init__(self, value=42):
print('12345',value)
def __del__(self):
print('123456')
t = Test('kkk') #输出12345 kkk 123456 - 说明t被销毁了
- 覆盖重写子类的constructor的时候,必须先调用超类的constructor,否则有可能无法正确地初始化. 通常是使用super()方法,不过对于一些老版本的Python代码,也可以直接调用超类的constructor.
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
self.hungry = False
print('I am Full now')
else:
print('I am not hungry')
class SongBird(Bird):
def __init__(self):
super().__init__()
# Bird.__init__(self) 旧版方法-通过类调用方法,就不会有实例与其相关联,因此便可以随意设置参数self.
# 这种方法调用的模式称为未关联方法调用.
s = SongBird()
s.eat()
s.eat()
- 使用super()方法的优点是显而易见的. 即使一个类有多个超类,也只需要调用super()一次(条件是所有超类的构造函数也使用super).同时,super()将返回一个超类的对象(类似于包含所有超类的合集的对象),当你尝试去访问super()返回的对象的某个属性或者方法时,Python将会在所有的超类中进行查找,直到找到该属性或者引发AttributeError异常.
Metadata
Metadata
Assignees
Labels
No labels