如何解决由重写方法引起的AttributeError

时间:2019-04-02 13:41:35

标签: python methods override super attributeerror

我尝试找出当我重写子类中的方法访问子类中引入的属性时出现属性错误的原因。

在下面的代码中,您可以看到B正常工作,但是仅当我在C中的重写方法中引用新属性时才会发生错误。

我以为我可能不得不再次调用populate方法,但是事实并非如此。

# some class that uses a method to populate one of it's attributes
class A:
    def __init__(self):
        self.populate()

    # The original populating method
    def populate(self):
        self.x = 5

my_obj = A()
print(my_obj.x)

# I can make a subclass that works fine AND has a new attribute
class B(A):
    def __init__(self):
        super().__init__()
        self.y = 9

    def populate(self):
        self.x = 5

my_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.z

my_obj = C()
print(my_obj.x)

1 个答案:

答案 0 :(得分:3)

问题是初始化对象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