如何初始化基(超)类?
class SuperClass(object):
def __init__(self, x):
self.x = x
class SubClass(SuperClass):
def __init__(self, y):
self.y = y
使用super 对象确保您获得方法解析顺序中的下一个方法(作为绑定方法)。在 Python 2 中,您需要将类名和 self 传递给 super 以查找绑定的 __init__ 方法:
class SubClass(SuperClass):
def __init__(self, y):
super(SubClass, self).__init__('x')
self.y = y
在 Python 3 中,有一个小魔法让 super 的参数变得不必要 - 作为一个附带好处,它的工作速度更快:
class SubClass(SuperClass):
def __init__(self, y):
super().__init__('x')
self.y = y
像下面这样对父级进行硬编码会阻止您使用协作多重继承:
class SubClass(SuperClass):
def __init__(self, y):
SuperClass.__init__(self, 'x') # don't do this
self.y = y
注意__init__ may only return None - 它旨在就地修改对象。
某事__new__
还有另一种初始化实例的方法——它是 Python 中不可变类型的子类的唯一方法。因此,如果您想继承 str 或 tuple 或其他不可变对象,则需要它。
你可能认为它是一个类方法,因为它有一个隐含的类参数。但它是actually a staticmethod。所以你需要用cls显式调用__new__。
我们通常从__new__ 返回实例,因此如果这样做,您还需要在基类中通过super 调用基类的__new__。因此,如果您同时使用这两种方法:
class SuperClass(object):
def __new__(cls, x):
return super(SuperClass, cls).__new__(cls)
def __init__(self, x):
self.x = x
class SubClass(object):
def __new__(cls, y):
return super(SubClass, cls).__new__(cls)
def __init__(self, y):
self.y = y
super(SubClass, self).__init__('x')
Python 3 回避了一些由 __new__ 是静态方法引起的超级调用的怪异之处,但您仍然需要将 cls 传递给未绑定的 __new__ 方法:
class SuperClass(object):
def __new__(cls, x):
return super().__new__(cls)
def __init__(self, x):
self.x = x
class SubClass(object):
def __new__(cls, y):
return super().__new__(cls)
def __init__(self, y):
self.y = y
super().__init__('x')