Python super()和@staticmethod交互
super()不应该与staticmethods一起使用吗 当我尝试像Python super()和@staticmethod交互,python,python-2.7,static-methods,super,Python,Python 2.7,Static Methods,Super,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.getl
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'
回溯(最近一次呼叫最后一次):
文件“asdf.py”,第13行,在
a=Second.getlist()
getlist中第9行的文件“asdf.py”
l=super(秒).getlist()
AttributeError:“super”对象没有属性“getlist”
如果我将staticmethods更改为classmethods,并将类实例传递给super(),则一切正常。我在这里是不是打错了super(type),还是我遗漏了什么 在对象实例上调用普通方法时,该方法将对象实例作为第一个参数接收。它可以获取tte对象的类及其父类,因此调用
super
是有意义的
在对象实例或类上调用classmethod
方法时,该方法将类作为第一个参数接收。它可以获取父类,因此调用super
是有意义的
但是当您调用staticmethod
方法时,该方法不会接收任何内容,也无法知道调用它的对象或类。这就是为什么您不能在静态方法中访问super
的简短答案
我在这里是不是打错了super(type),还是我遗漏了什么?
是的,你打错电话了。。。而且(事实上,因为)有些东西你错过了
但是不要难过;这是一门极其困难的学科
报告指出
如果省略第二个参数,则返回的超级对象将解除绑定。
未绑定的super
对象的用例非常狭窄和罕见。有关Michele Simionato对super()
的讨论,请参见以下文章:
- (这一条专门涵盖未绑定的超级链接)
super
我说你称之为“错误的”(虽然没有上下文,正确性基本上是没有意义的,而且一个玩具示例也没有给出太多上下文)。由于未绑定的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)
,因为第二个继承了第一个表单,你可以使用第一个.getlist()
,而不是在super中传递两个参数(即super)(第二,第二)
)
这在Python3中有什么不同吗?在Python3中,没有任何参数的
super()
是在常规方法中调用它的常用方式。我在Python3中调用super().foo()时遇到了同样的问题。
@gerrit:Python3的零参数super()
仅适用于类或实例方法。这是因为它使用魔法来确定在哪个类中定义它。在静态方法中(就像在常规的模块级函数中一样),您仍然需要两个显式参数。(在Python 3中,单参数形式仍然是未绑定的。)但是,如果您以后更改祖先,这可能会搞砸。例如,如果在继承树中的第一个和第二个之间添加了一个中间类OnePointFive
,Second
,则在调用以前的超级类时会跳过一个级别。
class First(object):
@staticmethod
def getlist():
return ['first']
class Second(First):
@staticmethod
def getlist():
# l = super(Second, Second).getlist()
l = First.getlist()
l.append('second')
return l
a = Second.getlist()
print (a)