當我覆蓋子類中訪問該子類中引入的屬性的方法時,我試圖找出出現 Attribute 錯誤的原因。在下面的代碼中,您可以看到B工作正常,但僅當我在C.我想我可能不得不再次調用 populate 方法,但事實并非如此。# some class that uses a method to populate one of it's attributesclass A: def __init__(self): self.populate() # The original populating method def populate(self): self.x = 5my_obj = A()print(my_obj.x)# I can make a subclass that works fine AND has a new attributeclass B(A): def __init__(self): super().__init__() self.y = 9 def populate(self): self.x = 5my_obj = B()print(my_obj.x)print(my_obj.y)class C(A): def __init__(self): super().__init__() self.z = 7 self.populate() # This method overides the original one and causes an attribute error # because self.z is unknown def populate(self): self.x = self.zmy_obj = C()print(my_obj.x)
1 回答

波斯汪
TA貢獻1811條經驗 獲得超4個贊
問題是x初始化對象時需要該屬性C。在A.__init__調用self.populate()中已經是覆蓋方法,即C.populate它需要self.x.
您可以self.z在調用父__init__方法之前進行設置:
class C(A):
def __init__(self):
self.z = 7
super().__init__()
def populate(self):
self.x = self.z
添加回答
舉報
0/150
提交
取消