Python 2.7超级方法无法看到子类名

时间:2015-11-18 10:52:45

标签: python python-2.7 oop super

得到如下代码:

class Type:
    def __init__(self, index):
        self.index = index

class MyCls(Type):
    def __init__(self, index):
        super(MyCls, self).__init__(index)

尝试编译后 - 在super行上收到了下一条错误消息:

  

详细信息名称错误:全局名称' MyCls'未定义

如何定义MyCls以使上述代码有效?

1 个答案:

答案 0 :(得分:3)

您展示的代码段不应触发NameError - 允许类以这种方式引用自己

但是,super仅适用于新式类 - 尝试实例化MyCls对象将引发TypeError。要解决此问题,类Type需要明确继承object

class Type(object):
    def __init__(self, index):
        self.index = index
在这种情况下,

MyCls可以保持原样。然后你有:

>>> a = MyCls(6)
>>> a
<__main__.MyCls object at 0x7f5ca8c2aa10>
>>> a.index
6
相关问题