【发布时间】:2017-05-09 16:51:48
【问题描述】:
我正在测试python的继承,我得到了这个:
__metaclass__=type
class b:
def __init__(s):
s.hungry=True
def eat(s):
if(s.hungry):
print "I'm hungry"
else:
print "I'm not hungry"
class d(b):
def __init__(s):
super(b,s).__init__()
def __mysec__(s):
print "secret!"
obj=d()
obj.eat()
运行时错误为:
Traceback (most recent call last):
File "2.py", line 17, in ?
obj.eat()
File "2.py", line 6, in eat
if(s.hungry):
AttributeError: 'd' object has no attribute 'hungry'
我无法理解这一点,因为“b”的超类在其 init 中有 s.hungry,而子类在其自己的“init" 为什么仍然,python 说“d”对象没有属性“饥饿”?
另一个困惑:错误消息将“d”视为一个对象,但我将它定义为一个类! 我有什么问题吗,如何让它发挥作用?
【问题讨论】:
-
在当前类上使用
super,而不是父类。即super(d, s).__init__() -
另外,我强烈建议不要在 Python 中使用单字母名称。我建议阅读python.org/dev/peps/pep-0008
-
python3中的super()很简单,不需要传参数。
-
一个类是一个对象,一个对象的类实例。你为什么要覆盖
d中的dunder init? - 删除它。
标签: python class inheritance attributes super