super() 不应该与静态方法一起使用吗?
当我尝试类似的事情时
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
我收到以下错误
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'
如果我将静态方法更改为类方法并将类实例传递给 super(),则一切正常。我在这里错误地调用 super(type) 还是我遗漏了什么?
最佳答案
简短的回答
Am I calling super(type) incorrectly here or is there something I'm missing?
是:是的,你叫错了......并且(确实,因为)你缺少一些东西。
但不要难过;这是一个极其困难的课题。
If the second argument is omitted, the super object returned is unbound.
unbound super
对象的用例极其狭窄和罕见。有关 super()
的讨论,请参阅 Michele Simionato 的这些文章:
- Things to Know About Python Super [1 of 3]
- Things to Know About Python Super [2 of 3] (这个特别涵盖了未绑定(bind)的 super )
- Things to Know About Python Super [3 of 3]
此外,他强烈主张从 Python 3 here 中删除未绑定(bind)的 super
.
我说你是在“不正确地”调用它(尽管在没有上下文的情况下正确性在很大程度上是没有意义的,而且一个玩具示例并没有给出太多的上下文)。因为未绑定(bind)的 super
非常罕见,并且可能完全不合理,正如 Simionato 所说,使用 super()
的“正确”方式是提供第二个参数.
在您的情况下,使您的示例工作的最简单方法是
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
l = super(Second, Second).getlist() # note the 2nd argument
l.append('second')
return l
a = Second.getlist()
print a
如果您认为这样看起来很有趣,那您就没有错。但我认为大多数人在看到 super(X)
时所期待的(或者当他们在自己的代码中尝试时所希望的)是 Python 给你的,如果你这样做 super(X, X)
.
关于python - super() 和@staticmethod 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788214/