python - 为什么我的 python 子类无法识别父类(super class)的属性?

标签 python class inheritance attributes super

我正在测试 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/

相关文章:

c++ - 通过继承实现接口(interface)

qt - QML继承

python - Python-Behave 中屏幕截图的自定义错误处理程序

python - 如何比较两个 DF 中的两列并保持一些列常量并打印行?

javascript - 如何在 JavaScript ES6 类中链接异步方法

Java-JPA : How can I create a table for each subclass but not for superclass?

python - 对 Pandas 数据框的多列进行条件过滤

python - 根据费马小定理解释代码以检查素数

ruby - 在 Ruby 中, "class ClassName < Base"行在此上下文中意味着什么

java - 对象内存管理 Python 与 Java