不要从Python的超级中获得预期的结果

时间:2012-02-16 12:31:44

标签: python

根据我的理解,函数super应该允许嵌套在另一个中的Class访问其父级的'self'。我可能错了,但这里有一个我想要实现的简单例子:

class Test:
     def __init__(self):
         self.message = "Hello World"
     class Print:
         def __init__(self):
             print super(Test, self).message


this = Test()
this.Print()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home1/users/joe.borg/<ipython-input-3-3eb5db70be43> in <module>()
----> 1 this.Print()

/home1/users/joe.borg/<ipython-input-1-cee67a2914c3> in __init__(self)
      4     class Print:
      5         def __init__(self):
----> 6             print super(Test, self).message
      7 

TypeError: must be type, not classobj

3 个答案:

答案 0 :(得分:5)

super应该用于调用给定类的mro(方法解析顺序)中的下一个方法(通常是父类的方法)。这与你想要做的完全不同。

除此之外,您的类是旧式类(它们不是子类对象),因此super会抱怨,因为它只适用于新式类。

答案 1 :(得分:4)

由于super仅适用于新式类,即明确扩展object的类,因此会引发错误。

此外,super allows you to delegate method calls to a parent or sibling class in a linearized inheritance tree。但是,嵌套类不受继承关系的约束;所以,即使你修正了错误(即允许TestPrint扩展object),super在这种情况下也不起作用。

答案 2 :(得分:0)

我得到了这样的预期结果:

class Test(object):
     def __init__(self):
         self.message = "Hello World"
class Print(Test):
         def __init__(self):
             print super(Print, self).message
相关问题