Python 3 继承问题

Python 3 Inheritance Issue

我是 Python 新手,我在继承和使用方面遇到困难 超级()

下面的代码给我这个错误

Exception has occurred: AttributeError 'ObjB' object has no attribute 'job'

但我不确定为什么 job 是 ObjB 的属性

测试代码是这样的..

class ObjA():
    def __init__(self, astr):
        self.name = astr
        self.decorate()

    def decorate(self):
        self.name = '['+self.name+']'

class ObjB(ObjA):
    def __init__(self, aname, ajob):
        super().__init__(aname)
        self.job = ajob

    def decorate(self):
        super().decorate()
        self.name = self.name + ' is a ' + self.job

test = ObjA('Fred')
print(test.name)

test2 = ObjB('Fred', 'Baker')
print(test2.name)

我期待的是这个

[Fred]
[Fred] is a Baker

在您的 ObjB.__init__() 方法中,您在设置 self.job = ajob 之前调用 super().__init__(aname),因此当调用 decorate 方法时,self.job 是尚未设置。尝试将 self.job = ajob 移到 __init__() 方法的前面,例如:

class ObjB(ObjA):
    def __init__(self, aname, ajob):
        self.job = ajob
        super().__init__(aname)

另一种解决问题的方法是完全消除 decorate() 方法:

class ObjA():
    def __init__(self, astr):
        self.name = '['+astr+']'


class ObjB(ObjA):
    def __init__(self, aname, ajob):
        super().__init__(aname)
        self.job = ajob
        self.name = self.name + ' is a ' + self.job

关键是当你在subclass中使用super调用baseclass中的__init__时,self传递给__init__ 是subclass ObjB的实例而不是ObjA。因此,ObjA__init__中的self.decorate()实际上调用了ObjB中的decorate方法,所以job没有定义。

super().__init__ 函数如下:ObjA.__init__(test2)

以下来自Python docs关于继承

Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.