Careful use of variable length parameters
Python supports variable-length parameter lists, which can be implemented by *arg, **kwargs these two special syntaxes. The following examples are used for variable length parameters:
* Use *args to implement the variable parameter list: *args with Accept
A parameter list wrapped as a tuple to pass a non-critical parameter, and the number of parameters can be arbitrary.
def sumfun (*args): Result
= 0
for x in args[0:]: result
+ = x return result
print Sumfun (2, 4)
pri NT Sumfun (1,2,3,4,5)
print Sumfun ()
Use **kwargs to receive a list of keyword parameters in a dictionary, where the dictionary's key-value pairs represent the parameter names and values of the mutable arguments, respectively.
def category_table (**kwargs):
for Name, value in Kwargs.items ():
print ' {0} is a kind of {1} '. Format (name, value) C9/>category_table (apple= ' fruit ', carrot= ' vegetable ')
category_table (BMW = ' car ')
In a function, the normal parameters, the default parameters, and the two types of variable parameters are defined.
def set_axis (x, y xlabel= ' x ', ylable= ' y ', *args, **kwargs): Pass
It is appropriate to use variable parameters in the following scenarios
def mydecorator (fun):
def new (*args, **kwargs): Return
Fun (*args, **kwargs) return
new
If the number of parameters is indeterminate, consider using variable-length parameters.
It is used to implement the polymorphism of a function or, in the case of inheritance, some methods in which the parent class needs to be invoked.
Class A (object):
def somefun (self, p1, p2):
Pass
class B (a):
def myfun (self, p3, *args, **kwargs):
Super (B, self). Somefun (*args, **kwargs)
This digest is from the 91 recommendations for writing high-quality code to improve Python programs