Write Python code, often encounter some problems, this side do a summary backup.
Not to be continued ...
1, the parameters of * and * * usage
*args and **kwargs are often seen in Python functions, but the actual usage is that * and **,args are just like variable names.
*args: Allow any number of arguments (>=0) to be passed to the Python function, shown in tuple type.
**kwargs: Parameters that allow any number of (>=0) Key-value formats to be passed, displayed in dict type.
Direct code-throwing is clearer:
>>> def Testforargs (arg0, *arg1, **arg2):
... Print (arg0, arg1, arg2) ...
#参数只有一个时
>>> Testforargs (1)
1 () {}
#多个参数情况
>>> Testforargs (1,2,3,4)
1 (2, 3, 4 {}
>>> Testforargs (1,2,3,4, key1= ' Mary ', key2= ' Haha ')
1 (2, 3, 4) {' Key1 ': ' Mary ', ' Key2 ': ' Haha '}< C13/>>>> Testforargs (key1= ' Mary ')
Traceback (most recent call last):
File "<stdin>", line 1, In <module>
Typeerror:testforargs () Missing 1 required positional argument: ' arg0 '
2, what is the function signature. How to keep the function signature after using the adorner.
Definition: A function consists of so many parts, function name, number of parameters, parameter type, return value.
A function signature consists of the number of parameters and its type.
When a function is overloaded, the difference between the function signature (that is, the number of arguments and the type) is used to distinguish the method that the caller is invoking.
Flip Code:
#-*-coding:utf-8-*-import functools #写一个函数装饰器 to cache the value of the function def cache (func): Cache_dict = {} # @functools. Wraps (func) def wrapper (*args, **kwargs): Key = Repr (*args, **kwargs) if key in Cache_ Dict:return Cache_dict[key] Else: #使用cache_dict缓存同一个sql的结果 Cache_dict[key] = Func (*args, **kwargs) return Cache_dict[key] wrapper.csrf_exempt = True Functools.update_wrapper (wrapp Er, func) return wrapper @cache def execute_query (SQL): Print (' hit DB ') return ' result ' #函数名是否发生变化, keep function signature PR int (execute_query) # <function execute_query at 0xb709c89c> print (execute_query (' select * from table1 ')) # hit DB #
Result #缓存过的key不再缓存 Print (execute_query (' select * from table1 ')] # result print (Execute_query (' select * from Table2 ')) # hit DB # result
Keep the function signature, using the wraps and Update_wrapper methods in Functools, which can be seen in the specific calling code.
If you do not invoke the Functools method, it is obvious that the method name of the print (execute_query) becomes wrapper.
3. When Python inherits, which layer of parent method is inherited.
The Python inheritance sequence follows the C3 algorithm, sorted by topology, and as long as the desired content is found in one place, the lookup is no longer continued.
Specifically look at this link:
https://kevinguo.me/2018/01/19/python-topological-sorting/
Reference Links:
Https://stackoverflow.com/questions/3394835/args-and-kwargs
Https://www.the5fire.com/functools-update-wrapper.html