__init__
如果除了当前类中正在执行的操作之外,您还需要从 super中完成某些操作,__init__,
您必须自己调用它,因为这不会自动发生。但是,如果您不需要 super 的__init__,
任何内容,则无需调用它。例子:
>>> class C(object):
def __init__(self):
self.b = 1
>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1
>>> class E(C):
def __init__(self):
self.a = 1
>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'
__del__
是相同的方式,(但要警惕依赖于__del__
完成 - 考虑通过 with 语句来代替)。
我很少用__new__.
我做所有的初始化__init__.