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

[Python basics 006] understand the advanced usage of Python functions

編輯:Python

Catalog

One 、 The namespace and scope of the function

1、 The namespace of the function

What is a namespace ?

Three classes of function namespaces

The order of loading and values among the three kinds of namespace

2、 The scope of the function

globals and locals Method

global keyword

Two 、 Nesting and scope chain of functions

Nested calls to functions

Nested definitions of functions

Scope chain of function

nonlocal keyword

global keyword

3、 ... and 、 The nature of function names

The function name is the memory address

Function names can be assigned

The function name can be used as an element of the container type

The function name can be used as the return value of the function

The function name can be used as an argument to the function

reflection  

Four 、 Closure

The concept of closure function

Judgment method of closure function

Closure nesting

Summary



One 、 The namespace and scope of the function

1、 The namespace of the function

  • What is a namespace ?

If there is a string of code , Observe the output :

def f():
a = 1
return a
print(a)
Output results :
Traceback (most recent call last):
File "E:/python Code /11/ Document I .py", line 4, in <module>
print(a)
NameError: name 'a' is not defined

Wrong report ! The error is “name 'a' is not defined”. Variable a Not defined ... Why? ? I defined it clearly a=1 ah !

Then we need to know Python What to do when the code runs into a function :

First of all, from the python After the interpreter starts executing , It opens up a space in memory whenever a variable is encountered , Record the corresponding relationship between variable name and value . But when it comes to a function definition, the interpreter just reads the function name into memory symbolically , It means you know the existence of this function , As for variables inside functions and logic interpreters, they don't care at all . When it comes to the function call ,python The interpreter will open up another block of memory to store the contents of this function , This is the time , We just focus on the variables in the function , The variables in the function will be stored in the newly opened memory . Variables in a function can only be used inside the function , And as the function completes , All the contents of this memory will also be emptied .

We give this “ Store the relationship between name and value ” There is a name for the space of —— It's called a namespace

The storage that the code creates at the beginning “ The relationship between variable name and value ” The space of is called Global namespace , The temporary space created in the internal operation of a function is called Local namespace

  • Three classes of function namespaces

Function namespaces are divided into three categories

1、 Built in namespace —— python Interpreter
# Namely python The names that the interpreter can use as soon as it starts are stored in the built-in namespace
# The built-in name is loaded into memory when the interpreter is started
2、 Global namespace —— We write code but not code in a function
# It is loaded into the memory in turn during the execution of the program from top to bottom
# Put all the variable names and function names we set
3、 Local namespace —— function
# It's the name of the function's internal definition
# When a function is called To generate this namespace As the function execution ends The namespace disappears again
# In part : You can use the global 、 Names in built-in namespaces
# In the global : You can use names in built-in namespaces , But it cannot be used locally
# Built in : Local and global names cannot be used 

Built in namespace : The built-in namespace holds Python The interpreter gives us the name ( function ) We don't need to define , All of them are familiar to us. Open the interpreter and you can use it directly, such as :input、print、str、set……

  • The order of loading and values among the three kinds of namespace

Loading order : Built in namespace ( Load the program before running > Global namespace ( The program is running : Load from top to bottom ) > Local namespace ( The program is running : Load when called )

        When calling locally : Local namespace > Global namespace > Built in namespace

        When called globally : Global namespace > Built in namespace

Example :

a = 10
def f():
a = 1
print(a)
f()
print(a)
Output results :
1
10

2、 The scope of the function

Scope is scope , According to the effective scope, it can be divided into global scope and local scope .

Global scope : contain Built in namespace 、 Global namespace , Can be referenced anywhere in the entire file 、 Global availability

Local scope : Local namespace , Only in local scope Inside take effect

  • globals and locals Method

locals():  The function returns all local variables in the current position as dictionary type .
globals():  The function returns all global variables in the current location as a dictionary type .

def func():
a = 1
print(locals())
print(globals())
print('======================== Split line ==========================')
func()
print(locals())
print(globals())

Output results :

  • global keyword

1、global yes Python Global variable keywords in .
2、 Variables are divided into local variables and global variables , Local variables can also be called internal variables .
3、 Variables created by an object or function are usually local variables , Can only be quoted internally , It cannot be referenced by other objects or functions .
4、 Global variables can be created by some object function , It can also be created anywhere in this program . Global variables can be referenced by all objects or functions in this program .
5、global Keyword is used to make a local variable a global variable

Example :

stay my Function , stay x Add in front global,my Function will x To assign as 8, In this case, the... In the global variable x Value change . It should be noted that global Need to be declared inside the function , If declared outside a function , The function still cannot operate x .

x = 4
def my():
global x
x = 8
print("x = ", x)
print("x = ", x)
my()
print("x = ", x)
The output is :
x = 4
x = 8
x = 8


Two 、 Nesting and scope chain of functions

  • Nested calls to functions

def max2(x,y):
m = x if x>y else y
return m
def max4(a,b,c,d):
res1 = max2(a,b)
res2 = max2(res1,c)
res3 = max2(res2,d)
return res3
ret = max4(1,2,4,3)
print(ret)
Output results :
4
  • Nested definitions of functions

def f1():
print("in f1")
def f2():
print("in f2")
f2()
f1()
Output results :
in f1
in f2
def f1():
def f2():
def f3():
print("in f3")
print("in f2")
f3()
print("in f1")
f2()
f1()
Output results :
in f1
in f2
in f3
  • Scope chain of function

a = 1
def outer():
a = 5
def inner():
a = 2
def inner2():
nonlocal a
a += 1
print('inner2',a)
inner2()
print('##a##:',a)
inner()
print('**a**:',a)
outer()
print(' overall situation :',a)
Output results :
inner2 3
##a##: 3
**a**: 5
overall situation : 1
  • nonlocal keyword

#nonlocal Only for local variables , Find the local variable in the upper layer closest to the current function, and there must be this variable outside
# The statement nonlocal The variable modification of the internal function of the will affect the local variables of the nearest level to the current function
# Invalid for global , Declare... In the inner function nonlocal A variable with the same name cannot appear before a variable
# Only the nearest layer is affected locally
def f1():
a = 1
def f2():
nonlocal a
a = 2
f2()
print('a in f1 : ',a)
f1()
Output results :
a in f1 : 2

  • global keyword

# For immutable data types You can view variables in the global scope locally
# But it can't be modified directly
# If you want to modify , You need to add... At the beginning of the program global Statement
# If in a local ( function ) There is a statement in global Variable , All local operations of this variable will be valid for global variables

3、 ... and 、 The nature of function names

  1. The function name is the memory address

  2. Function names can be assigned

  3. The function name can be used as an element of the container type

  4. The function name can be used as the return value of the function

  5. The function name can be used as an argument to the function

def func():
print(123)
func()
print(func)
# The function name is the memory address
# Function names can be assigned
func2 = func
func2()
# The function name can be used as an element of the container type
l = [func,func2]
for i in l:
i()
def func():
print(123)
def wahaha(f):
f()
return f # The function name can be used as the return value of the function
qqxing = wahaha(func) # The function name can be used as an argument to the function
qqxing()
Output results :
123
<function func at 0x000001ADF9946280>
123
123
123
123
123

  • reflection  

If I define a input function ( effect : Call this function to print ' Next week ovo'), Will it work with the built-in input There are conflicting functions ?

def input(a):
print(' Next week ovo')

So how does the next code work ?

def input(a):
print(' Next week ovo')
def func():
input(' Please enter ')
print(input)
func()

answer :


Four 、 Closure

  • The concept of closure function

The internal function contains a reference to the name of the external scope rather than the scope of the whole play , This internal function is called a closure function
# Functions defined internally are called internal functions

Because of the scope , We can't get the variables and functions inside the function . What if we just want to do it ? Go back !

If we want to use variables inside a function outside the function , You can return this variable directly , So what if we want to call the function inside the function outside the function ? Just use the function name as the return value

def outer():
a = 1
def inner():
print(a) # An internal function calls an external variable a
return inner
inn = outer()
inn()
Output results :
1

  • Judgment method of closure function

The method of judging closure function __closure__

When running , If there is cell Words , It means that it is a closure function . If not, it's not .

# Output __closure__ Yes cell Elements : It's a closure function
def func():
name = 'eva'
def inner():
print(name)
print(inner.__closure__)
return inner
f = func()
f()
# Output __closure__ by None : It's not a closure function
name = 'egon'
def func2():
def inner():
print(name)
print(inner.__closure__)
return inner
f2 = func2()
f2()
Output results :
(<cell at 0x000001E935CB0FA0: str object at 0x000001E935CC2CB0>,)
eva
None
egon

  • Closure nesting

As the name suggests, two or more closure functions are nested together

def wrapper():
money = 10
def func():
name = 'zhou'
def inner():
print(name,money) # Refer to the func() Function name Variable references wrapper() Function money Variable
return inner
return func
f = wrapper()
i = f()
i()
Output results :
zhuo 10


Summary

#func( A function name ) --->> The memory address of the corresponding function
# Function name ()--- Function call
# The memory address of the function ----() Function call
# There are two scopes
# Global scope —— It works on the whole —— Names in both the built-in and global namespaces belong to the global scope ——globals()
# Local scope —— It works locally —— function ( Names in the local namespace belong to the local scope ) ——#locals()globals() : Always print the global name
#locals() : What output according to locals The position of
# Define as few global variables as possible in your code , Use return values and receive return values
# Nesting of functions :
         Nested calls
         Nesting definition : Functions defined internally cannot be called globally directly
# The nature of function names :
         It's just a variable , Save the memory address where the function is located
# Closure :
         The internal function contains a reference to the name of the external scope rather than the scope of the whole play , This internal function is called a closure function 

Finally, thank you for seeing here :

In an unpublished article, Lu Xun said :“ If you understand the code, you must operate it yourself, so that you can better understand and absorb .”
One last sentence : A man can succeed in anything he has unlimited enthusiasm , Let's make progress together


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