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

Python notes 12- nature of functions & closures & scope of variables

編輯:Python

One 、 The nature of functions 【 Focus on mastering 】

A function is a variable , You can reassign , It can be used as an argument to a function , It can also be used as the return value of a function

# 1. A function is a variable
print(abs(-66)) # Function call ,66
print(abs) # The function itself ,<built-in function abs>
print(type(abs)) # <class 'builtin_function_or_method'>
r1 = abs(-66)
print(r1)
r2 = abs
print(r2)
# Be careful 1: The function itself is a variable , Function names can be assigned directly to other variables , After the assignment , You can use this variable to call the function
print(r2(-88)) # 88
f = int
print(f('234'))
def test():
print("test~~~~")
f = test
f()
# 2. Function names can be reassigned
# Be careful 2: When customizing variable names , Try to avoid duplicate names with system keywords or function names , Such as :list(),int(),str(),dict()
# abs = 'abc'
# print(type(abs)) # <class 'str'>
# print(abs(-99))
# 3. Function can be used as an argument to another function
numlist = ['fafa','agahaha','23']
numlist.sort(key=len) # len(xx)
print(numlist)
def func1(a,b,f):
total = f(a) + f(b)
return total
r = func1(34,-6,abs)
print(r)
# 4. Function can also be used as the return value of another function
def func1(a,b,f):
total = f(a) + f(b)
return f
f1 = func1(345,67,abs)
print(f1) # <built-in function abs>
print(f1(-19))
# summary : A function is a variable , A function name is a variable name , As long as the variable can operate , All functions are OK

Two 、 Closure 【 Focus on mastering 】

 A function is just a piece of executable code , After compiling “ curing ” 了 , Each function has only one instance in memory , Get the entry point of the function and you can execute the function . Functions can also be nested , That is, you can define another function inside a function , With the structure of nested functions , The closure problem arises
# 1. demand : stay func2 Function func1 Medium num1 Variable
# Mode one : Set return value , Get the return value by calling the function
# def func1():
# num1 = 10
# return num1
# def func2():
# print(func1())
# func2()
# Mode two : Nested definition of functions , You can go directly to
def func1():
num1 = 10
def func2():
print(num1)
print("*" * 50)
# 2. How nested defined functions call
# Mode one : Call directly in an external function
def outer1():
print(" External function ~~~~1111")
num1 = 10
def inner1():
print(" Internal function ~~~~1111")
print(num1)
inner1()
outer1()
print("*" * 50)
# Mode two : Set the return value for the external function . The return value is the internal function
def outer1():
print(" External function ~~~~1111")
num1 = 10
def inner1():
print(" Internal function ~~~~1111")
print(num1)
return inner1
f1 = outer1()
print(f1) # <function outer1.<locals>.inner1 at 0x1084e16a8>
f1()
print("*" * 50)
# 3. Closure
"""
Concept : If two functions are nested in the definition , If an internal function accesses a variable in an external function , Will form a closure
"""
# a.
def outer1():
print(" External function ~~~~1111")
num1 = 10
def inner1():
print(" Internal function ~~~~1111")
print(num1)
return inner1
f1 = outer1()
print(f1)
f1()
print("*" * 50)
# b.
def outer1(a):
print(" External function ~~~~1111")
num1 = 10
def inner1():
print(" Internal function ~~~~1111")
print(num1,a)
return inner1
f1 = outer1(8)
print(f1)
f1()
print("*" * 50)
# c.
def outer1(a):
print(" External function ~~~~1111")
num1 = 10
def inner1(b):
print(" Internal function ~~~~1111")
print(num1,a,b)
return inner1
f1 = outer1(8)
print(f1)
f1(78)
print("*" * 50)
# d.
def outer1(a):
print(" External function ~~~~1111")
num1 = 10
def inner1(b):
print(" Internal function ~~~~1111")
print(num1,a,b)
return a + b
return inner1
f1 = outer1(8)
print(f1)
r = f1(78)
print(r)
"""
summary :
a. A closure is a nested definition of a function
b. Determine whether it is a characteristic of closure : Whether the internal function accesses the variables in the external function
c. A closure is essentially a function , So the default parameters used in ordinary functions , Key parameters , Variable length parameters and return values can be used
"""

3、 ... and 、 Scope of variable 【 Focus on mastering 】

1. Scope classification

The scope of a variable refers to the range that a variable can use

Program variables are not accessible anywhere , Access depends on where this variable is defined

The scope of a variable determines which part of the program can access which specific variable name .

【 Interview questions 】Python There are a total of 4 Kind of , Namely

L:Local, Local scope , Special internal function
E:Enclosing, Function scope 【 In functions other than internal functions 】
G:Global, Global scope
B:Built-in, Built in scope 【 Built-in scope 】 num = int("244")

How to find it : With L—>E—>G—>B, I can't find , Then I will go to the part outside the part to find ( Such as closures ), If you can't find it, you will go to the whole situation , Then go to build in to find

# Size of access rights :global > enclosing > local
# 1. No duplicate name
num1 = 10 # Global scope :global, Can be accessed anywhere in the current file
def outer1():
num2 = 20 # Function scope :enclosing, Can only be accessed in external functions
def inner1():
num3 = 30 # Local scope :local, Can only be accessed in internal functions
print(num1,num2,num3)
print(num1,num2)
return inner1
f1 = outer1()
f1()
print(num1)
print("*" * 50)
# 2. The nuptial
# Be careful : When the variable names in different scopes are the same , The principle of proximity is followed during the visit
num = 10
def outer1():
num = 20
def inner1():
num = 30
print("inner:",num) # 30
print("outer:",num) # 20
return inner1
f1 = outer1()
f1()
print('global:',num) # 10
# 3.
"""
Be careful :
Python There are only modules in (module)、 class (class) And function (def、lambda) To introduce a new scope ,
Other code blocks , for example if/elif/else、try/except、for/while No new scope will be introduced ,
In other words, the variables defined in these statements , It can also be used externally
"""
def func():
n = 10
# print(n)
if 1:
m = 19
print(m)
for _ in range(10):
a = 24
print(a)

2. Local and global variables

Variables defined within a function have a local scope , Define a global scope outside the function .

Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope

# Be careful : Global variables and local variables are relative definitions
# Global variables : Can be accessed anywhere in the current file
# local variable : Can only be accessed within the specified scope
# 1.
num1 = 34 # Global variables
def test1():
num2 = 10 # local variable
# 2.
num1 = 23 # Global variables
def test2():
num2 = 6 # local variable 【 Function scope 】
def inner():
num3 = 10 # local variable 【 Local scope 】
# 3.【 Interview questions 】
# a. In the following definition , Two a Represent different variables
# When the variable names in different scopes are the same , visit 【 obtain 】 The principle of proximity is followed in the process of
a = 15
def check():
a = 88
print(a) # 88
check()
print(a) # 15
print("*" * 50)
# b.
# a = 15
# def check():
# a += 88 # UnboundLocalError: local variable 'a' referenced before assignment
# print(a)
# check()
# print(a)

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