python - super() 和@staticmethod 交互

标签 python python-2.7 static-methods super

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?

是:是的,你叫错了......并且(确实,因为)你缺少一些东西。

但不要难过;这是一个极其困难的课题。

documentation注意到

If the second argument is omitted, the super object returned is unbound.

unbound super 对象的用例极其狭窄和罕见。有关 super() 的讨论,请参阅 Michele Simionato 的这些文章:

此外,他强烈主张从 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/

相关文章:

python - 使用 Django 和 Reportlab 从 HTML 生成 PDF

python - 如何用 matplotlib 画一条线?

python - 在 Python 中使用 SHA256 对字节字符串进行签名

python-2.7 - AWS python lambda 函数 :No module named requests

python - 值错误: time data does not match format (convert part of string to time)

c++ - 访问修饰符是否适用于静态类函数?

python - Discord Bot - "Attribute Error: ' NoneType' 对象没有属性 'strip.'

python - 在 Python 中加载 C 共享库期间出现 OSError( undefined symbol :checkedCalloc)

swift - 如何在 Swift 中调用符合协议(protocol)的泛型类型的静态方法

oop - 什么时候应该在类中使用静态方法?有什么好处?