python中的super().__init__()
子类构造函数调用super().init()
class Person: def __init__(self, name = 'Person'): self.name = name class Puple(Person): # 直接继承Person,可调用name pass class Puple_Init(Person): # 继承Person,覆盖父类__init__方法,增加age属性 def __init__(self, age): # 不可调用name属性 self.age = age class Puple_Super(Person): # 继承Person,改写__init__方法,增加age属性 def __init__(self, name, age): # 可调用name属性 # super(Class, self).method() super(Puple_Super, self).__init__(name) self.age = age
pp = Puple() PP_i = Puple_Init(10) PP_s = Puple_Super('Puple_Super', 12) pp.name pp_i.name pp_s.name
结果
Person
Traceback (most recent call last):
File "D:/desktop/111.py", line 26, in <module>
print(PP_i.name)
AttributeError: 'Puple_Init' object has no attribute 'name'
Puple_Super
快去成为你想要的样子!