Generics, if you have tasted java, you should be familiar with him. But you may not know that simple generic functions can also be implemented in Python (3.4+).
In Python, only the specific implementation method can be selected based on the data type of a single (first) parameter. The official name is single-dispatch
. You may not understand it. In human terms, it is possible to realize that the data type of the first parameter is different, and the function it calls is also different.
singledispatch
It was introduced in PEP443. If you are interested in it, PEP443 should be the best learning document: https://www.python.org/dev/peps/pep-0443/
Its use is extremely simple, as long as the singledispatch
decorated function is a single-dispatch
generic function of ( generic functions
).
- Single dispatch : The act of performing the same operation in different ways according to the type of a parameter.
- Multiple dispatch : The behavior of a special function can be selected according to the types of multiple parameters.
- Generic function : multiple functions are tied together to form a generic function.
Here is a simple example.
from functools import singledispatch
@singledispatch
def age(obj):
print('请传入合法类型的参数!')
@age.register(int)
def _(age):
print('我已经{}岁了。'.format(age))
@age.register(str)
def _(age):
print('I am {} years old.'.format(age))
age(23) # int
age('twenty three') # str
age(['23']) # list
Results of the
我已经23岁了。
I am twenty three years old.
请传入合法类型的参数!
Speaking of generics, in fact, not uncommon in some built-in functions Python itself, such as len()
, iter()
, copy.copy()
, pprint()
etc.
You may ask, what use is it? In fact, it's really useless. If you don't use it or don't know it, it won't affect your coding at all.
Let me give you an example, you can feel it.
Everyone knows that there are many data types in Python, such as str, list, dict, tuple, etc. The splicing methods of different data types are different, so here I wrote a general function that can be based on the corresponding data type Select the corresponding splicing method for splicing, and for different data types, I should also be prompted that splicing is not possible. The following is a simple implementation.
def check_type(func):
def wrapper(*args):
arg1, arg2 = args[:2]
if type(arg1) != type(arg2):
return '【错误】:参数类型不同,无法拼接!!'
return func(*args)
return wrapper
@singledispatch
def add(obj, new_obj):
raise TypeError
@add.register(str)
@check_type
def _(obj, new_obj):
obj += new_obj
return obj
@add.register(list)
@check_type
def _(obj, new_obj):
obj.extend(new_obj)
return obj
@add.register(dict)
@check_type
def _(obj, new_obj):
obj.update(new_obj)
return obj
@add.register(tuple)
@check_type
def _(obj, new_obj):
return (*obj, *new_obj)
print(add('hello',', world'))
print(add([1,2,3], [4,5,6]))
print(add({'name': 'wangbm'}, {'age':25}))
print(add(('apple', 'huawei'), ('vivo', 'oppo')))
# list 和 字符串 无法拼接
print(add([1,2,3], '4,5,6'))
The output is as follows
hello, world
[1, 2, 3, 4, 5, 6]
{'name': 'wangbm', 'age': 25}
('apple', 'huawei', 'vivo', 'oppo')
【错误】:参数类型不同,无法拼接!!
If you don't use singledispatch, you might write such code.
def check_type(func):
def wrapper(*args):
arg1, arg2 = args[:2]
if type(arg1) != type(arg2):
return '【错误】:参数类型不同,无法拼接!!'
return func(*args)
return wrapper
@check_type
def add(obj, new_obj):
if isinstance(obj, str) :
obj += new_obj
return obj
if isinstance(obj, list) :
obj.extend(new_obj)
return obj
if isinstance(obj, dict) :
obj.update(new_obj)
return obj
if isinstance(obj, tuple) :
return (*obj, *new_obj)
print(add('hello',', world'))
print(add([1,2,3], [4,5,6]))
print(add({'name': 'wangbm'}, {'age':25}))
print(add(('apple', 'huawei'), ('vivo', 'oppo')))
# list 和 字符串 无法拼接
print(add([1,2,3], '4,5,6'))
The output is as follows
hello, world
[1, 2, 3, 4, 5, 6]
{'name': 'wangbm', 'age': 25}
('apple', 'huawei', 'vivo', 'oppo')
【错误】:参数类型不同,无法拼接!!
I recommend my original " PyCharm Chinese Guide " e-book, which contains a large number (300) of illustrations . It is well-made and worthy of a collection by every Python engineer.
The address is: http://pycharm.iswbm.com