AttributeError:'child'对象没有属性'_name'

Raf*_*del 0 python inheritance python-2.7 python-3.x

我是Python的初学者,并试图理解类继承.但是,当我尝试以下代码时,我收到此错误:

AttributeError: 'child' object has no attribute '_name'
Run Code Online (Sandbox Code Playgroud)

这是代码:

class parent:
    def __init__(self):
        self._name = "Smith"

    @property
    def name(self):
        return self._name

class child(parent):
    def __init__(self, childname):
        self._childname = childname

    def getname(self):
        return "child : {} .. parent : {}".format(self._childname, super().name)

def main():
    Dad = parent()
    Son = child("jack")
    print(Son.getname())

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

这是为什么 ?我正确理解Python中的类继承吗?

Mor*_*enn 6

您的问题实际发生在这里:

def getname(self):
    return "child : {} .. parent : {}".format(self._childname, super().name)
Run Code Online (Sandbox Code Playgroud)

更确切地说,super().name是罪魁祸首:不仅super()没用,而且你应该打电话name()而不是name,但如果你看代码name(),你会发现它使用了变量_name.

但是,_name在父__init__方法中初始化.如果你想要它被调用,你应该总是__init__在子节点中调用父方法,它不是自动完成的.你的孩子__init__方法应该是:

class child(parent):
    def __init__(self, childname):
        super().__init__()
        self._childname = childname
Run Code Online (Sandbox Code Playgroud)