重载是指函数名一样,但是参数类型或者个数不一样。
其实python也可以实现重载
使用 functools模块的singleddispatch函数,单分派机制。
见例子:
from functools import singledispatch
@singledispatch
def to_str(obj):
print('%r'%(obj))
# to_str是上面标记的基函数,函数参数类型是作为register的参数传入,从而实现重载
@to_str.register(int)
def _(obj): # 专门函数的名称无关紧要,所以使用`_`这个占位符即可。并且切记不要和基函数名字一样,否则会覆盖。
print('Integer: %d'%(obj))
@to_str.register
def _(obj:str): #使用
print('String: %s'%(obj))
@to_str.register(list)
def _(obj):
print('List: %r'%(obj))
if __name__ == "__main__":
to_str(1)
to_str('hello')
to_str(range(3))
to_str(object)
单python的重载只有第一个参数的不同类型会被重载。后面的参数的类型变化会被自动忽略。
另外,默认值也是python用来实现函数重载的重要方法。参数的个数不同的重载完全靠默认值可以实现