可能重复:
子类__init__覆盖超类的
class A():
z = 'z it is'
def __init__(self):
self.a = 'a it is'
class B(A):
def __init__(self):
self.b = 'b it is'
b = B()
print b.z # z it is
print b.a # AttributeError: B instance has no attribute 'a'
b
是继承自A
类的B
类的实例。这是否意味着我可以访问父类的属性?
您需要显式调用超类__init__
。它不会自动调用。
类B中的__init__
函数应该这样写:
class B(A):
def __init__(self):
A.__init__(self)
self.b = "b it is"