我在测试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”的超类在其in I t中有s.hungry,而子类在其自身的init中调用“super”
为什么python仍然说“d”对象没有“hungry”属性?
另一个困惑是:错误消息将“d”视为一个对象,但我将其定义为一个类!
我做错什么了吗,怎么做?
最佳答案
class d(b):
def __init__(s):
super(d,s).__init__()
def __mysec__(s):
print ("secret!")
Document:
对于这两种用例,典型的超类调用如下所示:
> class C(B):
> def method(self, arg):
> super(C, self).method(arg)