Python:同名的常规方法和静态方法 [英] Python: Regular method and static method with same name
问题描述
我有一个Python类,其中包含许多方法。我想要这些方法之一有一个静态对应,即,一个静态方法具有相同的名称 - 可以处理更多的参数。经过一些搜索,我发现我可以使用 @staticmethod
装饰器来创建一个静态方法。
I have a Python class, which contains a number of methods. I want one of those methods to have a static counterpart—that is, a static method with the same name—which can handle more arguments. After some searching, I have found that I can use the @staticmethod
decorator to create a static method.
为了方便起见,我创建了一个简化的测试用例,可以重现问题:
For convenience, I have created a reduced test case which reproduces the issue:
class myclass:
@staticmethod
def foo():
return 'static method'
def foo(self):
return 'public method'
obj = myclass()
print(obj.foo())
print(myclass.foo())
我希望上面的代码打印以下内容:
I expect that the code above will print the following:
public method
static method
打印以下内容:
public method
Traceback (most recent call last):
File "sandbox.py", line 14, in <module>
print(myclass.foo())
TypeError: foo() missing 1 required positional argument: 'self'
从这里,我只能假设调用 myclass.foo()
试图调用它的非静态对应没有参数因为非静态方法总是接受参数 self
)。这个行为阻碍了我,因为我期望任何调用静态方法来实际调用静态方法。
From this, I can only assume that calling myclass.foo()
tries to call its non-static counterpart with no arguments (which won't work because non-static methods always accept the argument self
). This behavior baffles me, because I expect any call to the static method to actually call the static method.
我测试了这个问题Python 2.7 和 3.3,只接收相同的错误。
I've tested the issue in both Python 2.7 and 3.3, only to receive the same error.
为什么会发生这种情况,我该怎么做来修复我的代码,使其打印:
Why does this happen, and what can I do to fix my code so it prints:
public method
static method
如我所料?
推荐答案
类似的问题在这里:在python编程中使用相同名称的重写方法
函数是通过名称查找的,所以你只需使用实例方法重新定义foo。在Python中没有诸如重载函数这样的东西。你可以用一个单独的名字写一个新的函数,或者你提供的参数可以处理两者的逻辑。
functions are looked up by name, so you are just redefining foo with an instance method. There is no such thing as an overloaded function in Python. You either write a new function with a separate name, or you provide the arguments in such a way that it can handle the logic for both.
换句话说,你可以没有静态版本和同名的实例版本。如果你看看它的 vars
,你会看到一个 foo
。
In other words, you can't have a static version and an instance version of the same name. If you look at its vars
you'll see one foo
.
In [1]: class Test:
...: @staticmethod
...: def foo():
...: print 'static'
...: def foo(self):
...: print 'instance'
...:
In [2]: t = Test()
In [3]: t.foo()
instance
In [6]: vars(Test)
Out[6]: {'__doc__': None, '__module__': '__main__', 'foo': <function __main__.foo>}
这篇关于Python:同名的常规方法和静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!