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):
print(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):
print(args)
print(kwargs)
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):
print(y)
def b(x, *args, y, **kwargs):
print(y) 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'
pass 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 :

print(help(recv))
# 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=[]):
print(b)
return b
x = spam(1)
x.append('oh!')
x.append('no!')
print(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")
return
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 .

reference

  • [1] https://www.python.org/
  • [2] Martelli A, Ravenscroft A, Ascher D. Python cookbook[M]. " O'Reilly Media, Inc.", 2005.

Python Technique 2: More articles on the advanced use of function parameters

  1. Python of use format Function format string usage

    This article mainly introduces Python of use format Function format string usage , The format string is Python Learn the basics , This paper mainly aims at Python2.7.x edition , Friends in need can refer to   since python2. ...

  2. Python Learning notes - Function parameter

    >>> def power(x): ... return x * x ... >>> power(5) 25 >>> def power(x, n ...

  3. Python Built in functions sorted() In advanced usage

    about Python Built in functions sorted(), Let's talk to list( list ) Member functions in list.sort() Make a comparison . In essence ,list Sorting and built-in functions for sorted It's sort of the same , Even the parameters are basically the same . ...

  4. python Basic function parameters , The name space , And function nesting

    Function advanced content outline : 1. Function parameter -- Dynamic transfer parameters 2. The name space , Local namespace , Global namespace , do ⽤ Use domain , Loading order . 3. Nesting of functions 4. gloabal , nonlocal keyword 1. Letter ...

  5. python Study day10 function Ⅱ( Parameters &amp; Scope )

    function Ⅱ( Parameters & Scope ) A summary of knowledge : py2 And py3 The difference between Logical operations ()>not>and>or String flip slice flip is And == difference git relevant Data type judgment operating system :cent ...

  6. python Transfer of function parameters in

    Reprinted from : http://winterttr.me/2015/10/24/python-passing-arguments-as-value-or-reference/ I think , This title may be for many beginners ...

  7. Python Learn the function parameters

    Previous section , We learned Python How to define and call functions and how to get the return value . When the function is called , Some functions require arguments to start the function , Some do not require parameters . In this section we will introduce Python What parameter types are there in . Positional arguments When the function is called ...

  8. python Basic function parameters 、 nesting 、 Return value 、 object 、 Namespace and scope

    The principle of using functions The use of functions must follow : The principle of defining before using Definition of function , Similar to the definition of variables , If you directly reference a function without defining it in advance, you are referring to a variable name that does not exist Define the stage : Only grammar is detected , No code execution , When a syntax error occurs ...

  9. The array name is used as the function parameter and sizeof usage

    source :https://blog.csdn.net/jay_zhouxl/article/details/51745518 int f(int *p,char *a) { printf("p[ ...

  10. Python Basic function parameters and return value advanced

    Parameter function : If the outside world wants to process the data inside the function , The data can be passed into the function as parameters : The return value is used to : If you want a function to finish executing , Report the execution result of the function to the outside world , You can use the return value of the function . The return value of the function Advanced Using yuan ...

Random recommendation

  1. Socket Programming practice (3) Multi connection server implementation and simple P2P Chat routine

    SO_REUSEADDR Options At the end of the last article, we posted a simple C/S Communication routines . In this example program , Use "Ctrl+c" At the end of the communication , The server cannot be restarted immediately , If you try to restart the server , Will be ...

  2. MyEclipse Rename in

    When we want to rename a function or variable , If you change it manually, it will be time-consuming and there may be some omissions , Causes compilation errors . In this case, it can be at the definition of variable or function , Press down MyEclipse Of Alter + SHIF + R rename , Then press Enter key ...

  3. UITabbar item Set up notes

    It's been written in code for a long time UITabbarController, Try to use xib Let's write about it once , But encountered tabbar item I don't know where to start when I customize the icon , For example, define before and after selection icon picture , This place is still not ...

  4. ResourceManager High availability configuration

    ResourceManager High availability configuration 1. yarn-site.xml To configure <property> <name>yarn.resourcemanager.cluster-id ...

  5. Get collection 、 After the array, it is necessary to judge whether it is empty and whether it is not after the object is created according to the constructor null Confirmation

    In the development process , Whenever you get a collection object , Before using or traversing the collection object , Whether it is null as well as size()>0 The judgment of the , But if size()>0 Words , If not, it can be explained that the collection object is not nu ...

  6. hive Time function

    I found that :1.datediff You can pass in timestamp Type parameter     Official document : Date Functions The following built-in date functions are ...

  7. The authenticity of host &#39;slaver2 (192.168.199.132)&#39; can&#39;t be established. RSA key fingerprint is cc:4e:23:01:ca:97:52:21:85:78:bc:29:ca:b3:12:52.

    1:ssh Sign in The authenticity of host 192.168.199.132 can't be established. The problem of The problem arises , It has to be solved , use Baidu Search , A lot of details , ...

  8. lettuce Behavior driven framework instance

    practice : One :e1_MyFirstBDD The factorial calculation is realized by using the method zero.feature: Feature: Compute factorial In order to play with Le ...

  9. PHP Export to Word Format

    <?php $file = './html.doc'; $table = '<table width="100%"><tr><td>'.i ...

  10. iis How to set up http Access steering https

    Set the website to https after , Found that after entering the domain name in the browser , You can't expect to see a successful visit to the page , In the input, such as :http://www.alipay.com The browser automatically navigates to https://www.alipay.com. ...