为什么我的 python subclass 无法识别来自 super class 的属性?
Why my python subclass doesn't recognize attribute from super class?
我正在测试 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" 的超级 class 在其 init 中有 s.hungry,而子 class 在其自身的“init”中调用 "super"
为什么 python 说 "d" 对象没有属性 'hungry'?
另一个困惑:错误信息将"d"当成对象,但我将其定义为class!
我是不是弄错了什么,如何让它发挥作用?
我想这就是您要找的:
__metaclass__=type
class b:
def __init__(self):
self.hungry=True
def eat(self):
if(self.hungry):
print "I'm hungry"
else:
print "I'm not hungry"
class d(b):
def __init__(self):
super(d,self).__init__()
def __mysec__(self):
print "secret!"
obj=d()
obj.eat()
class d(b):
def __init__(s):
super(d,s).__init__()
def __mysec__(s):
print ("secret!")
For both use cases, a typical superclass call looks like this:
> class C(B):
> def method(self, arg):
> super(C, self).method(arg)
我正在测试 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" 的超级 class 在其 init 中有 s.hungry,而子 class 在其自身的“init”中调用 "super" 为什么 python 说 "d" 对象没有属性 'hungry'?
另一个困惑:错误信息将"d"当成对象,但我将其定义为class! 我是不是弄错了什么,如何让它发挥作用?
我想这就是您要找的:
__metaclass__=type
class b:
def __init__(self):
self.hungry=True
def eat(self):
if(self.hungry):
print "I'm hungry"
else:
print "I'm not hungry"
class d(b):
def __init__(self):
super(d,self).__init__()
def __mysec__(self):
print "secret!"
obj=d()
obj.eat()
class d(b):
def __init__(s):
super(d,s).__init__()
def __mysec__(s):
print ("secret!")
For both use cases, a typical superclass call looks like this:
> class C(B):
> def method(self, arg):
> super(C, self).method(arg)