Python 2.7 super方法看不到子class名字

Python 2.7 super method can't see child class name

得到如下代码:

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

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

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

Detail NameError: global name 'MyCls' is not defined

我应该如何定义 MyCls 才能使上面的代码工作?

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

但是,super 仅适用于新式 classes - 尝试实例化 MyCls 对象将引发 TypeError。要解决此问题,class 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