我有这个:
#! /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__
问题:根据上述文档,我做错了什么。我对文件的理解差距在哪里?
答案 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)