0

我有这个:

#! /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__

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

4

2 回答 2

1

__new__由于__new__是静态方法,因此通常不使用 Super 。此时对象甚至还不存在,因此没有 super 可以调用。

具体覆盖方法参考发行说明__new__

于 2013-08-25T00:22:21.853 回答
1

您基本上需要替换objectmyclass1in ss = super(object,cls)object没有超类。 myclass1做。您还需要argsss.__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是您想要获取其超类的类。不是超类本身。如果您已经知道超类或想要为固定的超类进行硬编码,您可以替换ssobject并编写:

        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)
于 2013-08-25T00:20:56.937 回答