Python, 超级()

Python, super()

我想了解 super() 在 2.7 中的工作原理。下面是我从 Whosebug 中获取的代码。请帮助我理解我做错了什么?

我先调用了Base,然后调用了ChildA。这些工作正常。调用 ChildB 时得到以下 error.TypeError:super() 参数 1 必须是类型,而不是 classobj

class Base():
    def __init__(self):
        print "Base Created"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(ChildA):
    def __init__(self):
        super(ChildB,self).__init__()

问题是您的 Base class 使用的是旧的 class 样式。为了使用 super 你的 Base class 需要继承 object 如下:

class Base(object):
    ...

你的 class ChildA 不使用 super 所以它可以工作,而 ChildB 使用 super 并因此生成 TypeError

你没有通过 childB 的 super class 更好的是你可以像这样使用 定义 called_class(): 打印 "Class assignment" return2

class 栏(对象): y = called_class()

def __init__(self, x):
    self.x = x

"Class assignment"

def called_instance(): 打印 "Instance assignment" return2

class Foo(对象): def init(self, x): self.y = called_instance() self.x = x

小节(1) 酒吧(2) 富(1)

"Instance assignment"

继承父子class的所有属性来访问