import functools
@functools.singledispatch()
def myfunc(arg):
print("default myfunc({!r})".format(arg))
@myfunc.register(int)
def myfunc_int(arg):
print("myfunc_int({})".format(arg))
@myfunc.register(list)
def myfunc_list(arg):
print('myfunc_list()')
for item in arg:
print(' {}'.format(item))
myfunc('string argument')
myfunc(1)
myfunc(2.3)
myfunc(['a', 'b', 'c'])
新函数的register()属性相当于另一个修饰符,用于注册替代实现。用singledispatch()包装的第一个函数就是默认实现,
在未指定其他类型特定函数时就使用这个默认实现,在这个例子中特定类型就是float
"""print
default myfunc('string argument')
myfunc_int(1)
default myfunc(2.3)
myfunc_list() a b c
"""
没有找到这个类型的完全匹配时,会计算继承顺序,并使用最接近的匹配类型
import functools
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B):
pass
class E(C,D):
pass
@functools.singledispatch
def myfunc(arg):
print("default myfunc({})".format(arg.__class__.__name__))
@mufunc.regigster(A)
def myfunc_A(arg):
print('myfunc_A({})'.format(arg.__class__.__name__))
@myfunc.register(B)
def myfunc_B(arg):
print('myfunc_B({})'.format(arg.__class__.__name__))
@myfunc.register(C)
def myfunc_C(arg):
print("myfunc_C({})".format(arg.__class__.__name__))
myfunc(A())
myfunc(B())
myfunc(C())
myfunc(D())
myfunc(E())
在这个例子中,类D和E与已注册的任何泛型函数都不完全匹配,所选择的函数取决于类层次结构
"""print
myfunc_A(A)
myfunc_B(B)
myfunc_C(C)
myfunc_B(D)
myfunc_C(E)
"""