为什么我的python子类不能识别超类的属性?

2024-10-01 13:45:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在测试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()

运行时错误如下:

^{pr2}$

我无法理解这一点,因为“b”的超类在其init中有s.hungry,而子类在它自己的“init内部调用”super“ 为什么python说“d”对象没有“hungry”属性?在

另一个困惑:错误消息将“d”视为一个对象,但我将其定义为一个类! 我有没有做错什么,怎么做?在


Tags: 对象trueobjifinitdeftype错误
2条回答
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:

^{pr2}$

我想这就是你想要的:

__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()

相关问题 更多 >