super()是不是要用于staticmethods?
当我尝试类似的东西
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
l = super(Second).getlist()
l.append('second')
return l
a = Second.getlist()
print a
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Traceback (most recent call last):
File "asdf.py", line 13, in <module>
a = Second.getlist()
File "asdf.py", line 9, in getlist
l = super(Second).getlist()
AttributeError: 'super' object has no attribute 'getlist'
Run Code Online (Sandbox Code Playgroud)
如果我将staticmethods更改为classmethods并将类实例传递给super(),那么一切正常.我在这里不正确地调用超级(类型)还是有些东西我不见了?
根据文件,
__new__()是一个静态方法(特殊的,因此您不需要声明它),它将请求实例的类作为其第一个参数.
它显然不是类方法,但通常看起来像一个,除了手动调用的任何客户端__new__需要显式传入类参数.例如:
>>> str.__new__()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
str.__new__()
TypeError: str.__new__(): not enough arguments
>>> str.__new__(str)
''
Run Code Online (Sandbox Code Playgroud)
但是替代对象创建API -例如,所有八个备选datetime构造 - 是平时classmethodS,SO是datetime.now()按预期工作.
为什么这样__new__设置?
我对这里的python文档中的以下示例感到有些困惑.
>>> class inch(float):
... "Convert from inch to meter"
... def __new__(cls, arg=0.0):
... return float.__new__(cls, arg*0.0254)
...
>>> print inch(12)
0.3048
>>>
Run Code Online (Sandbox Code Playgroud)
据推测,float在这里是在Python内部深处定义的实际float类.当我们调用时float.__new__(cls, argument),我们偷偷地调用返回给定参数的float实例的函数,但是我们将它传递给inch类而不是float类.由于英寸级别没有真正做任何事情,为什么这样做?