使用超级新风格类的困惑

时间:2013-08-25 00:04:40

标签: python

我有这个:

#! /usr/bin/env python

class myclass1(object):

        def __new__(cls,arg):
                print cls, arg, "in new"
                ss = super(object,cls)
                print ss, type(ss)
                ss.__new__(cls,arg)
#                super(object,cls).__new__(cls,arg)
#                return object.__new__(cls,arg)


        def __init__(self,arg):
                self.arg = arg + 1
                print self, self.arg, "in init"




if __name__ == '__main__':

        m = myclass1(56) 

它出错了:

$ ./newtest.py 
<class '__main__.myclass1'> 56 in new
<super: <class 'object'>, <myclass1 object>> <type 'super'>
Traceback (most recent call last):
  File "./newtest.py", line 23, in <module>
    m = myclass1(56)
  File "./newtest.py", line 9, in __new__
    ss.__new__(cls,arg)
TypeError: super.__new__(myclass1): myclass1 is not a subtype of super

错误有效。我明白了。但是我现在很困惑文档在这个页面上为__new__所说的内容:http://docs.python.org/2.6/reference/datamodel.html#object.__new__

问题:根据上述文档,我做错了什么。我对文件的理解差距在哪里?

2 个答案:

答案 0 :(得分:1)

您基本上需要将object替换为myclass1中的ss = super(object,cls)object没有超类。 myclass1。您还需要从args移除ss.__new__(cls,args),因为object.__new__只有一个参数cls。最终代码应为:

        def __new__(cls,arg):
                print cls, arg, "in new"
                ss = super(myclass1,cls)
                print ss, type(ss)
                ss.__new__(cls)
#                super(object,cls).__new__(cls,arg)
#                return object.__new__(cls,arg)

您对文档理解的差距是super的第一个参数是您要获取其超类的类。不是超类本身。如果你已经知道超类或者想要修改一个固定的超类,你很可能已经用ss替换了object并写了:

        def __new__(cls,arg):
                print cls, arg, "in new"
#               ss = super(myclass1,cls)
                print object, type(object)
                object.__new__(cls)
#                super(object,cls).__new__(cls,arg)
#                return object.__new__(cls,arg)

答案 1 :(得分:1)

由于__new__是静态方法,因此__new__中通常不会使用

超级。此时对象甚至还不存在,因此没有超级调用。

有关覆盖__new__

的具体方法,请参阅release notes