Function
- The Python function does not have a return statement, and implicitly returns a value of None
- A function is a callable object, callable ()
function parameters
- Parameters that are passed in when arguments are called match the number of definitions (variable parameter exceptions)
- Position parameters
- def f (x, Y, z) call using F (1, 3, 5)
- Incoming arguments in order of parameter definition
- Keyword parameters
- def f (x, Y, z) calls using F (x=1, y=3, z=5)
- Use the name of the formal parameter to enter and exit the argument, and if the parameter name is used, then the order of the parameters can be different from the order of the definition
- Pass the reference
- Requires that the positional parameter be passed in before the keyword parameter, which is the position parameter
function parameter Default value
- When defined, follow a value after the formal parameter
- Role
- The default value of a parameter can be assigned to a default value without a given parameter when sufficient arguments are not passed in
- With very many parameters, it is not necessary for the user to enter all parameters each time, simplifying the function call
Variable parameters
A formal parameter can match any parameter
- Using * Before the formal parameter indicates that the parameter is a mutable argument and can receive multiple arguments
Collect multiple arguments as a tuple
Variable parameters for keyword parameters
- Use the * * symbol before the formal parameter to indicate that you can receive multiple keyword parameters
- The collected argument names and values form a dictionary
- Positional variable parameters and keyword variable parameters
- Positional variable parameters use an asterisk before the formal parameter *
- Keyword variadic use two asterisk * before formal parameter * *
- Positional variable parameters and keyword mutable parameters can all collect several arguments, positional variable parameters are collected to form a tuple, and keyword variable parameter collection forms a Dict
- When mixing parameters, the variable parameter is placed at the end of the parameter list, and the normal parameter needs to precede the parameter list, where the variable parameter needs to be preceded by the keyword variable
Keyword-only parameters
- If after an asterisk parameter, or a positional variable parameter, the common parameter that appears is actually not the normal parameter, but the keyword-only parameter
def fn(*args, x):print(x)print(args)
def(**kwargs, x):print(x)print(kwargs)
Direct reporting of grammatical errors
Can be understood as Kwargs will intercept all the keyword parameters, even if you write x=5,x will never get this value, so syntax error
- Another form of the keyword-only parameter
def fn(*, x,y):print(x,y)fn(x=5,y=6)
After the * number, the normal parameter becomes the keyword-only argument that must be given.
Variable parameter and parameter default values
def fn(*args, x=5):print(x)print(args)
Parameter rules
- Parameter list parameter General order is, normal parameter, default parameter, variable position parameter, keyword-only parameter (can with default value), variable keyword parameter
Parametric deconstruction
function return value and scope return value of the function
function nesting
- Another function is defined in one function
- The function has a visible scope, which is the concept of scopes
- An intrinsic function cannot be used externally, it throws a Nameerror exception because it is not visible
Scope
Global scope
- Visible throughout the program's running environment
Local scope
- Visible inside functions, classes, and so on
- Local variables cannot be used beyond the local scope in which they reside
- Outer variable scope visible within scope of the inner layer
In the inner scope inner, if o=97 is defined, it is equivalent to redefining a new variable o in the current scope, but this o does not overwrite the O in the outer scope outer
- Global variables Globals
#x = 5def foo():global xx = 10x += 1 # 报错吗?print(x) # 打印什么?print(x) #打印什么?
- Using variables from the global keyword, declare the x within Foo to use the x defined in the outer global scope
However, an assignment of x = 10 is defined, in which the internal scope assigns a value to the variable x of an outer scope, not a new variable in the internal scope, so x+=1 does not give an error. Note that the scope of x here is still global
- X+=1 is this the cause of the special form of error? After the reference is assigned, the Python dynamic language is assigned to the definition before it can be referenced. Workaround, add an assignment statement such as x=0 before this statement, or use global to tell the internal scope to find the variable definition
An internal scope uses an assignment statement such as X = 5 to redefine the variable x that is used by the local scope, but once the scope uses global declaration x to be globally, then x=5 is equivalent to assigning a value to the variable x for the global scope
- Global usage Principles
- An external scope variable is visible inside the scope, but not directly in the local scope of the inner domain, because the function is designed to be encapsulated and isolated from the outside world.
- If the function requires the use of an external global variable, use the function's parameter-pass argument to resolve
- Bottom line: Don't use global. Learning it is to understand the scope of variables in depth
Closures (Key Concepts)
- Free variable: A variable that is not defined in the local scope. For example, a variable that defines the scope of an outer function outside the memory function
- Closures: A concept that appears in nested functions, meaning that the inner layer function refers to the free variable of the outer function, and the closure is formed. Many languages have this concept, the most familiar is JavaScript
- The use of global can be solved, but this is using the globals, not the closures
- If you want to close a normal variable, you can use nonlocal in Python3
nonlocal keywords
- The nonlocal keyword is used to mark a variable as not defined in the local scope, but defined in a level local scope of the ancestor, but not in the global scope
Scope of default values
The function is also an object, and Python places the default value of the function in the attribute, which accompanied with the entire life cycle of the function object
- Property defaults uses tuples to save all positional parameter defaults, and it does not change because it is used in the function body
Use dictionary in property kwdefaults to save default values for all keyword-only parameters
- This default value can be modified by using a mutable type as the default value
Sometimes this trait is good, sometimes this trait is bad, there are side effects
- The first of these methods
- Create a new object with a shadow copy and never change the parameters passed in
def foo(xyz=[], u=‘abc‘, z=123):xyz = xyz[:] # 影子拷贝xyz.append(1)print(xyz)foo()print(foo.__defaults__)foo()print(foo.__defaults__)foo([10])print(foo.__defaults__)foo([10,5])print(foo.__defaults__)
function body without changing the default value
XYZ is a copy of an incoming parameter or default parameter, and if you want to modify the original parameter, you can do nothing
- The second method of
- You can choose to create or modify incoming objects flexibly by judging the value.
- This approach is flexible and widely used
- Many of the definitions of functions can be seen using the immutable value of None as the default parameter, it can be said that this is a customary method
def foo(xyz=None, u=‘abc‘, z=123): if xyz is None: xyz = [] xyz.append(1) print(xyz)foo()print(foo.__defaults__)foo()print(foo.__defaults__)foo([10])print(foo.__defaults__)foo([10,5])print(foo.__defaults__)
Use immutable type default values
If you use the default value of None, create a list
If you pass in a list, modify the list
Variable name resolution principle LEGB
- Local, native scope, local namespace of the domain scope. Function call is created, call ends extinct
- A nested function is introduced in enclosing,python2.2, which implements the closure, which is the namespace of the outer function of the nested function.
- Global scope, which is the namespace of a module. Created when the module is import and dies when the interpreter exits
- Build-in, the namespace of the built-in module, the life cycle is created when the Python interpreter starts and dies when the interpreter exits. For example, print (open), print and open are built-in variables
- So the search order for a noun is legb.
Destruction of functions
Recursive
anonymous functions
[x for x in (lambda *args: map(lambda x: x+1, args))(*range(5))] [x for x in (lambda *args: map(lambda x: (x+1,args), args))(*range(5))]
Python Fourth Week study notes (1)