我想知道一个类中是否可以有两个名称相同的方法(如果可以执行我想要的操作,则只有一个) 但是第一个方法将被调用class().method()
和class.method()
上的第二个(下面的示例)。
我试图通过创建一个带有@staticmethod
的方法和另一个不带有第二个方法(具有相同名称)的方法来实现它。
这是我的例子:
class MyClass:
# @potential_decorator1
def my_function():
print("MyClass.my_function() has been called !")
# @potential_decorator2
def my_function(self):
print("Now it's MyClass().my_function() that has been called !")
我尝试过的事情:
class MyClass:
@staticmethod
def my_function():
print("MyClass.my_function() has been called !")
def my_function(self):
print("Now it's MyClass().my_function() that has been called !")
但是当我测试它时:
>>> MyClass.my_function()
TypeError: my_function() missing 1 required positional argument: 'self' #I'd like the
#staticmethod to be called instead
>>> MyClass().my_function()
Now it's MyClass().my_function() that has been called !
通过分析,我了解到“经典”方法将覆盖静态方法。