Python中一个类中同名方法的处理
我怎么能在一个类里声明几个方法,它们的名字是一样的,但参数的数量或者类型不同呢?
我需要在下面这个类里做哪些修改呢?
class MyClass:
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
def my_method(self,parameter_A_that_Must_Be_String):
print parameter_A_that_Must_Be_String
def my_method(self,parameter_A_that_Must_Be_String,parameter_B_that_Must_Be_String):
print parameter_A_that_Must_Be_String
print parameter_B_that_Must_Be_String
def my_method(self,parameter_A_that_Must_Be_String,parameter_A_that_Must_Be_Int):
print parameter_A_that_Must_Be_String * parameter_A_that_Must_Be_Int
12 个回答
27
在使用Python 3.5或更高版本时,你可以用@typing.overload
来给重载的函数或方法添加类型注解。
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
<actual implementation>
33
你不能这样做。没有重载、多个方法或者类似的东西。一个名字只能指代一个东西。就语言本身来说,你总是可以自己模拟这些功能……你可以用 isinstance
来检查类型(但请正确使用,比如在 Python 2 中,使用 basestring
来同时检测字符串和unicode),不过这样做看起来很丑陋,一般不推荐,而且很少有用。如果这些方法做的事情不同,就给它们起不同的名字。还可以考虑多态性。
91
你可以创建一个函数,这个函数可以接收不定数量的参数。
def my_method(*args, **kwds):
# Do something
# When you call the method
my_method(a1, a2, k1=a3, k2=a4)
# You get:
args = (a1, a2)
kwds = {'k1':a3, 'k2':a4}
所以你可以这样修改你的函数:
def my_method(*args):
if len(args) == 1 and isinstance(args[0], str):
# Case 1
elif len(args) == 2 and isinstance(args[1], int):
# Case 2
elif len(args) == 2 and isinstance(args[1], str):
# Case 3