【发布时间】:2013-05-13 17:54:47
【问题描述】:
我是 Python 的初学者,并试图理解类继承。但是当我尝试下面的代码时,我得到了这个错误:
AttributeError: 'child' object has no attribute '_name'
这是代码:
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()
这是为什么呢?我是否正确理解 Python 中的类继承?
【问题讨论】:
-
用
__name__代替_name怎么样? -
__xxx__形式的名称保留供 Python 本身使用。 -
您是否真的在尝试编写在 Python 2.7 和 Python 3.x 中运行的代码?如果没有,你想回答哪一个? (在这种情况下会有所不同。)
标签: python inheritance python-2.7 python-3.x