我正在测试 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”的父类(super class)在它的init 中有 s.hungry,而子类在它自己的“init<”中调用“super”/强>” 为什么 python 仍然说“d”对象没有属性“饥饿”?
另一个困惑:错误信息将“d”当成一个对象,但我将它定义为一个类! 我有没有做错什么,如何让它发挥作用?
最佳答案
class d(b):
def __init__(s):
super(d,s).__init__()
def __mysec__(s):
print ("secret!")
Document :
For both use cases, a typical superclass call looks like this:
> class C(B):
> def method(self, arg):
> super(C, self).method(arg)
关于python - 为什么我的 python 子类无法识别父类(super class)的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41310647/