我试图在Python中实现方法重载:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow(2)
但是输出是第二种方法2;类似的:
class A:
def stackoverflow(self):
print 'first method'
def stackoverflow(self, i):
print 'second method', i
ob=A()
ob.stackoverflow()
给了
Traceback (most recent call last):
File "my.py", line 9, in <module>
ob.stackoverflow()
TypeError: stackoverflow() takes exactly 2 arguments (1 given)
我该怎么做呢?
在Python中,你不这样做。当人们在像Java这样的语言中这样做时,他们通常需要一个默认值(如果他们不需要,他们通常需要一个具有不同名称的方法)。所以,在Python中,你可以有默认值。
class A(object): # Remember the ``object`` bit when working in Python 2.x
def stackoverflow(self, i=None):
if i is None:
print 'first form'
else:
print 'second form'
如您所见,您可以使用它来触发单独的行为,而不仅仅是使用默认值。
>>> ob = A()
>>> ob.stackoverflow()
first form
>>> ob.stackoverflow(2)
second form
在MathMethod.py文件中:
from multipledispatch import dispatch
@dispatch(int, int)
def Add(a, b):
return a + b
@dispatch(int, int, int)
def Add(a, b, c):
return a + b + c
@dispatch(int, int, int, int)
def Add(a, b, c, d):
return a + b + c + d
在Main.py文件
import MathMethod as MM
print(MM.Add(200, 1000, 1000, 200))
我们可以使用multipledispatch重载该方法。
我用Python 3.2.1写了我的答案。
def overload(*functions):
return lambda *args, **kwargs: functions[len(args)](*args, **kwargs)
工作原理:
Overload接受任意数量的可调用对象,并将它们存储在元组函数中,然后返回lambda。
接受任意数量的参数,
然后返回存储在函数[number_of_unnamed_args_passed]中的调用函数的结果,并将参数传递给lambda。
用法:
class A:
stackoverflow=overload( \
None, \
#there is always a self argument, so this should never get called
lambda self: print('First method'), \
lambda self, i: print('Second method', i) \
)