Python technique 2: advanced usage of function parameters

lonelyprince7 2021-10-29 00:45:13
python technique advanced usage function

1、 Key parameters (positional argument) And position parameters (keyword argument)

Python The parameters of the function are based on the function In the call ( Be careful , When not a function definition ) The form of parameter transfer is divided into keyword parameters and location parameters .

(1) Key parameters :

Keyword parameters refer to when passing parameters in a function call , By identifier ( Such as name=) Boot parameters , Or put it in a place by ** Pass in the guided Dictionary . As shown below :

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

(2) Positional arguments

Parameters that are not keyword parameters are location parameters . It's passed on separately , It can also be placed in a place by * Guided iterative sequence ( list 、 Tuples etc. ) Deliver in . As shown below :

complex(3, 5)
complex(*(3, 5))

Positional arguments are always placed at the top of the function's argument list , Keyword parameters must be placed after positional parameters . The positional relationship between them is as follows :

def func(arg1, arg2, kwarg1, kwarg2):
func(1, 2, kwarg1=3, kwarg2=4)

here arg1、arg2 It's a position parameter ,kwarg1,kwarg2 It's a keyword parameter . Keyword parameter key( That's what we have here 'kwarg1=3' Medium 'kwarg1','kwarg2=4' Medium 'kwarg2') Ensure that the name is consistent with the formal parameter .

2、 Accept any number of parameters

(1) Accept any number of positional parameters

"*" In addition to the previous chapter, we talked about splitting iteratable objects of any length , It can still be in Function definition Use in , Used to define a function that can accept any number of position parameters , As shown below :

def avg(first, *rest):
return (first + sum(rest)) / (1 + len(rest))
print(avg(1, 2, 3, 4, 5))
# (2, 3, 4, 5)
# 1. 5

"*" The first argument must be used as the last positional argument , And "*" The first parameter passed in is the tuple data structure .

(2) Accept any number of keyword parameters

Want to accept any number of keyword parameters , We can use... In a similar way "**" Parameters at the beginning . As shown below :

import html
def make_element(name, value, **attrs) -> str:
key_values = [ ' %s="%s"' % item for item in attrs.items()]
attr_str = ''.join(key_values)
# Perform a string formatting operation.
element = '<{name} {attrs}>{value}</{name}>'.format(name=name, attrs=attr_str, value=html.escape(value))
return element
res_1 = make_element('item', 'Albatross', size='large', quantity=6)
res_2 = make_element('p', '<spam>') # escape Will put here '<spam>' Medium '<' and '>' Replace with a safe sequence &lt; &gt;
print(res_1) # <item size="large" quantity="6">Albatross</item>
print(res_2) # <p >&lt;spam&gt;</p>

"**" The first parameter must be used as the last keyword parameter , And "**" After the first parameter is passed in, the dictionary data structure .

(3) Accept any number of location parameters and keyword parameters at the same time

If you want the function to accept any number of positional and keyword parameters at the same time , As long as it is used in combination "*" and "**" that will do .

def anyargs(*args:tuple, **kwargs:dict):
anyargs(2, 3, 4, 5, time=1, data=2)
# (2, 3, 4, 5)
# {'time': 1, 'data': 2}

3、keyword-only Parameters

As I said before ,"*" The leading parameter can only be used as the last position parameter ,"**" The leading parameter can only be used as the last keyword parameter ( Nature is also the last parameter ), And infer from this "*" The parameter after the first parameter must be a keyword parameter .

# Appear in the *args The following parameter is called keyword-only Parameters
# In these two examples y Can only be keyword parameters , When passing parameters, ensure that key Consistency with formal parameters
def a(x, *args, y):
def b(x, *args, y, **kwargs):
a(4, 6, 7, 8, y=1)
b(4, 6, 7, 3, y=1, data=2, year=3)
# 1
# 1

Such a parameter is called keyword-only Parameters , It appears in *args Subsequent parameters can only be used as keyword parameters .
We can make full use of this nature , Put the keyword parameter in the with * After the leading parameter , Or a single one * after , The caller of the forced function must pass the keyword parameter , Like the following :

def recv(max_size, *, block):
'Receives a message'
recv(1024, True) # recv2() takes 1 positional argument but 2 were given
# and missing 1 required keyword-only argument: 'block'
recv(1024, block=True) # OK

This technology is used in practical projects , It can be used to specify keyword parameters for functions that accept any number of positional parameters , For example, the following minimum function with truncation function . there clip Parameters are forced to be passed in as keyword parameters , And set a default value None, Make the parameter optional . As shown below :

def mininum(*values, clip=None):
m = min(values)
if clip is not None:
m = clip if clip > m else m
return m
res1 = mininum(1, 5, 2, -5, 10)
res2 = mininum(1, 5, 2, -4, 10, clip=0)
print(res1, res2) # -5, 0

besides ,keyword-only Parameters can improve code readability , Write a function like this :

msg = recv(1024, False)

If the reader of the code is not familiar with recv How functions work , Then you may not understand the False What is the function of parameters , If the call of this function can be written as follows , That's much clearer ( Of course , The writer of this function needs to force the user of the function to write like this from the beginning ):

msg = recv(1024, block=False)

Last , If Function definition It is mandatory to use keyword-only Parameters , So when a user requests help information , Parameter information can be displayed naturally :

# Help on function recv in module __main__:
# recv(max_size, *_, block)
# Receives a message

3、 Optional parameters ( Parameters with default values )

To define an optional parameter , Need to be in Function definition Assign values to parameters in , And ensure that the default parameter appears at the end of the parameter list . Like this :

def spam(a, b=42):
print(a, b)
spam(1) # 1, 42
spam(1, 2) # 1, 2

If the default is a variable container , For example, list 、 aggregate 、 Dictionary, etc , Need to put None As default : As shown below :

def spam(a, b=None):
if b is None:
b = []

Caution 1: Never write directly like this :

def spam(a, b=[]):

If you write like that , Then something will happen that you don't expect to see : If the default value is changed outside the function body , Then this modification will still haunt the function calls later , This is shown below :

def spam(a, b=[]):
return b
x = spam(1)
# []
# ['oh!', 'no!']
# ['oh!', 'no!']

Caution 2: In the body of a function , We often need to judge whether the parameter is None, You need to use is Operator , Never write directly like this :

def spam(a, b=None):
if not b:
b = []

The problem here is : Even though None Will be judged as False, But there are many other objects ( For example, the length is 0 String 、 list 、 Tuples 、 Dictionary, etc ) There is also such behavior . such , There are many other specific inputs that will also be judged as False, Then the value that should have been passed in by the user is directly defaulted [] It's covered . As shown below :

def spam(a, b=None):
if not b:
b = []
spam(1) # OK
x = []
spam(1, x) # Oops! x will be overwritten by default []
spam(1, 0) # Oops! 0 will be overwritten by default []
spam(1, '') # Oops! '' will be overwritten by default []

Last , Let's talk about a very difficult problem . We want to detect in the function whether the caller provides a specific value for the optional parameter ( It could be any value ,None Also calculate ) such , Naturally, we can't use None,0, False As the default value, and then do the test again , Because users themselves may take them as parameters .
To solve this problem , You can write like this :

_no_value = object()
def spam(a, b=_no_value):
if b == _no_value:
print("No b value supplied")
print(a, b)
spam(1) # No b value supplied
spam(1, 2) # 1 2
spam(1, None) # 1 None

here _no_value Is based on object() Class to create a unique object , You can use this to detect the parameters provided by the user , Because it's almost impossible for users to _no_value Object as parameter input ( Unless the user passes in the same object , Or even object Other objects of type are all related to _no_value The object is different ).
Here is a brief description object class ,object yes Python The base class for almost all objects in ,object Object has no data ( Bottom missing __dict__ Dictionaries , You can't even set any properties ), Its only function is to detect equality .


  • [1]
  • [2] Martelli A, Ravenscroft A, Ascher D. Python cookbook[M]. " O'Reilly Media, Inc.", 2005.

  1. django 自定義中間件如何忽略部分視圖函數
  2. python map函数的使用
  3. python map函數的使用
  4. Utilisation de la fonction de carte Python
  5. 通过对于Arduino或是Python(包括相关库)的使用,结合自己的日常工作,描述相关知识在工作中起到了什么作用。
  6. 2021最全Python接口测试自动化教程【附学习资料】
  7. Python读取配置文件(config.ini),写入配置文件
  8. Python lit le profil (config.ini), écrit le profil
  9. python 两个数据列表匹配查找
  10. python 兩個數據列錶匹配查找
  11. Recherche de correspondance de deux listes de données Python
  12. python循环结构程序编写题目
  13. 【算法学习】1603. 设计停车系统(java / c / c++ / python / go / rust)
  14. Problèmes de programmation de la structure de la boucle Python
  15. 有人能用python写出代码吗wwww
  16. [apprentissage de l'algorithme] 1603. Conception du système de stationnement (Java / C / C + + / python / go / Rust)
  17. Python中if和else,总是显示无效语法是缩进问题吗?是的话可以详细讲解一下吗?
  18. Python的问题,希望有人帮帮忙
  19. Python的問題,希望有人幫幫忙
  20. J'espère que quelqu'un peut m'aider.
  21. Si et autrement en python, est - ce un problème d'indentation d'afficher toujours une syntaxe invalide? Oui, puis - je vous expliquer en détail?
  22. Quelqu'un peut écrire du Code en python?
  23. Dataframe数据,用pandas.to_excel导出成excel问题
  24. Données du cadre de données, en utilisant Exporter Excel vers un problème Excel
  25. 请问这个过期的要怎么弄呀,Python是下载的3.10版本的
  26. 請問這個過期的要怎麼弄呀,Python是下載的3.10版本的
  27. Qu'est - ce qu'on fait de ce vieux python?
  28. Python数据处理转置问题??
  29. Problèmes de transposition du traitement des données python??
  30. 使用python的pdfkit把html转pdf时,echarts无法显示
  31. python利用3维的0,1矩阵再matplotlib中画图
  32. Pycham developing Django project template tutorial
  33. Libraries commonly used in Python data analysis
  34. Python utilise une matrice tridimensionnelle 0, 1 pour redessiner les graphiques dans matplotlib
  35. 预备知识-python核心用法常用数据分析库(上)
  36. 預備知識-python核心用法常用數據分析庫(上)
  37. 我在python上创建了个web静态服务器,把一个前端页面,放进去然后在静态服务器上访问只出现了前段页面的代码,代码运行正常,这是怎么回事
  38. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅰ)
  39. 预备知识-python核心用法常用数据分析库(上)
  40. J'a i créé un serveur Web statique sur Python, j'ai mis une page frontale, j'ai accédé au Code sur le serveur statique qui n'avait que des pages frontales, et le Code fonctionnait correctement
  41. 预备知识-python核心用法常用数据分析库(下)
  42. python 文件排版,怎么控制写入在对应文件的位置(要写吐了,真是服了)
  43. Preliminary Knowledge - Python Core use Common Data Analysis Library (ⅰ)
  44. Typographie de fichiers Python, comment contrôler l'écriture à l'emplacement du fichier correspondant (pour écrire et vomir, vraiment pris)
  45. python:例题求解,不知道怎么等输入完所有数字后再输出
  46. 用python来实现:根据实际查询结果补充完整数据
  47. Mise en œuvre en python: compléter les données complètes en fonction des résultats réels de la requête
  48. python对excel进行分组但不进行聚合统计操作,且输出到不同的表格中?
  49. Python regroupe Excel, mais n'effectue pas de statistiques agrégées, et l'affiche dans différents tableaux.
  50. python如何提交,不要用太复杂的函数
  51. Comment soumettre Python sans utiliser de fonctions trop complexes
  52. Python,数据文件操作问题,想要代码
  53. python 提取多个字符串中的多个字段
  54. python 读入用户输入的一组正整数,到-1结束
  55. Python lit un ensemble d'entiers positifs entrés par l'utilisateur, se terminant par - 1
  56. 测试逐飞的MM32F3277 MicroPython开发板的基本功能
  57. Python timer reference
  58. 关于#python#的问题:python3队列维护
  59. Developing Hongmeng equipment program using python (3-prototype of security system)
  60. Questions sur # # Python #: maintenance de la file d'attente Python 3