程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python3 tutorial: variable input parameters for functions

編輯:Python

Usually we python When you define a function in , We need to give explicit function input parameters , For example, for a mathematical function z=f(x,y) It means ,z It's about x and y A function of . But for functions with unknown parameters , For example, the function form can be z=f(x,y), But it can also be z=f(x,y,m,n,i,j,k), When you're not sure you're in , You can use python Medium *args and **kwargs Parameters .

*args How to use parameters

Let's start with an example *args The basic usage of , This parameter can replace the fixed variable in the function bracket , In terms of data structure, it's a variable length tuple:

def fargs(*args):
s = 0
for variable in args:
s += float(variable)
return s
if __name__ == '__main__':
import sys
args_string = ''
for number in sys.argv[1:]: # Get parameters of any length from the command line 
args_string += number
args_string += ','
s = eval('fargs({})'.format(args_string)) # Executing functions directly with strings 
print ('The sum of {} is: {}'.format(args_string, s))

In this case , We not only introduced *args How to use , Command line parameter acquisition and eval Function these two python The common use of skills . How to get command line parameters , You can refer to this blog . The execution effect of the above code is as follows :

[[email protected]-manjaro args]$ python3 test_args.py 1 2 3 3.14
The sum of 1,2,3,3.14, is: 9.14
[[email protected]-manjaro args]$ python3 test_args.py 1 2 3 3.14 0.86
The sum of 1,2,3,3.14,0.86, is: 10.0

Here are two different lengths of input , By function fargs Finished the work of summation , And the length of the input is variable .

**kwargs Usage of

kwargs The usage of is similar to that described above *args Of , The difference lies in kwargs It's essentially an introduction of “ Dictionaries ”, Or a key value pair . It should be noted that , Here, the data format of each key value pair is tuple Type of , instead of python Dictionary type in , So it says “ Dictionaries ” Put quotation marks on it . Reference examples are as follows :

''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
def fkwargs(**kwargs):
s = 0
print ('Key values input: ',kwargs)
for key, variable in kwargs.items():
s += float(variable)
return s
if __name__ == '__main__':
import sys
args_string = ''
for number in sys.argv[1:]:
args_string += number
args_string += ','
s = eval('fkwargs({})'.format(args_string))
print ('The sum of {} is: {}'.format(args_string, s))

In this scenario, we set it as a function to calculate the total price of vegetables , The input parameters are each item purchased and its price , The final output is the total purchase price , The test results are shown below :

[[email protected]-manjaro args]$ python3 test_kwargs.py egg=20 beaf=60 milk=10
Key values input: {
'egg': 20, 'beaf': 60, 'milk': 10}
The sum of egg=20,beaf=60,milk=10, is: 90.0
[[email protected]-manjaro args]$ python3 test_kwargs.py egg=20 water=1
Key values input: {
'egg': 20, 'water': 1}
The sum of egg=20,water=1, is: 21.0

summary

In order to make the input parameters more extensible ,python In the args and kwargs The two methods , Can be used to represent a tuple Variable length input parameter of type . among args Is the input of a series of unary variables ,kwargs Is the input of a series of key value pairs , It can be considered as the input of a binary variable . Although these two schemes can also be implemented by themselves tuple To replace , However, using these two definitions directly will save a lot of tedious work of customizing variable input parameters .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved