1. Passing Parameters
Parameters are passed by assigning values to the local variable name.
Immutable parameters are passed through "values": modifying variables in a function is not passed to external variables.
Variable objects are passed through pointers: modifying variables in a function will be passed to external variables.
This is similar to the C language.
See the following example:
A = 1
B = ["some",]
Def changer (x, y ):
X = 3
Y [0] = "spam"
Changer (a, B)
Print a, B
Numbers are immutable objects, while lists are mutable objects. The running result is as follows:
1 ['spam']
The consequence of automatically passing in an object parameter for value assignment is the same as running a series of simple value assignment statements. The effect of calling the first parameter x is as follows:
A = 1
X =
X = 2
Print
Although x = 2 references the same object before running x and a, x points to 2 objects when x = 2 modifies the x variable.
The printed result is still 1.
If you do not want to change the mutable object, you can assign a value to the variable B during the call. You can use changer (a, B [:]) or convert it to the remote ancestor object changer (, tuple (B ))
2. Parameter Matching
Parameter Matching involves location, keyword, default, variable parameter, and variable parameter unpacking.
2.1 location parameters are the most commonly used and simple. They are the same as function calls in other languages.
2.2 Key Parameters
Def f (a, B, c ):
Return a, B, c
Print f (B = 1, c = 2, a = 3)
In this way, the location of the Link parameter is no longer needed. If you want to mix the location parameter and keyword, the keyword parameter must be after the location parameter:
Def f (a, B, c ):
Return a, B, c
Print f (1, c = 2, B = 3)
But this is not the case:
Def f (a, B, c ):
Return a, B, c
Print f (1, c = 2, a = 3)
Because parameter a has been automatically assigned a value through location. The following error is reported:
TypeError: f () got multiple values for keyword argument 'A'
2.3 default parameters
Def f (a, B = 2, c = 3 ):
Return a, B, c
Print f (1)
Print f (1, 4)
Print f (6, 7, 8)
Running result:
(1, 2, 3)
(1, 4, 3)
(6, 7, 8)
2.4 any parameter
* Args supports any number of parameters in the function, and ** args supports converting any number of keyword parameters into dictionaries.
Def min1 (test, * args ):
Res = args [0]
For arg in args [1:]:
If arg <res:
Res = arg
Return res
Def min2 (first, * rest ):
Res = first
For arg in rest:
If arg <res:
Res = arg
Return res
Def min3 (* args ):
Tmp = list (args)
Tmp. sort (reverse = False)
Return tmp [0]
Def f (a, ** dargs ):
Return a, dargs
Print f (1, B = 2, c = 3)
Result: (1, {'C': 3, 'B': 2 })
2.5 unpack Parameters
L = [3, 4]
D = {'D': 1, 'C': 2}
Def f (a, B, c, d ):
Return a, B, c, d
Print f (* L, ** D)
Output result: (3, 4, 2, 1)
The following example:
Def func1 (a, B, c = 3, d = 4 ):
Print a, B, c, d
Func1 (a, * (5, 6 ))
Output result: 1 5 6 4
Share: