python中functools.singledispatch的使用

来源:互联网 发布:微积分 清华 知乎 编辑:程序博客网 时间:2024/06/03 08:37

在python3中提供了functools.singledispatch这个装饰器,但是这个装饰器是做什么呢?其实它是单分派泛函数,看到这个名词,一脸的懵逼,这是什么鬼,然而大家都知道c++中的函数是可以重载的,那么它的作用就和c++中函数的重载类似。下面看个代码就知道它的作用了

from functools import singledispatch@singledispatchdef show(obj):    print (obj, type(obj), "obj")@show.register(str)def _(text):    print (text, type(text), "str")@show.register(int)def _(n):    print (n, type(n), "int")show(1)show("xx")show([1])

结果

1 <class 'int'> intxx <class 'str'> str[1] <class 'list'> obj

结论:通过上述代码的结果可以知道,为show函数传递不同的类型参数,就表现不同的行为,这c++的函数重载很类似。

原创粉丝点击