table of Contents
Function object
Everything in python objects
Quote
def f1():
print('from f1')
func = f1
print('f1:', f1)
print('func', func)
# 打印结果:
f1: <function f1 at 0x000002110991D268>
func <function f1 at 0x000002110991D268>
As a function parameter
def f1():
print('from f1')
def f2(f2_f1):
print('f2_f1:', f2_f1)
f2(f1)
print('f1:', f1)
# 打印结果:
f2_f1: <function f1 at 0x000001E47029D268>
f1: <function f1 at 0x000001E47029D268>
As a function return value
def f1():
print('from f1')
def f2(f2_f1):
return f2_f1
res = f2(f1)
print('res:', res)
print('f1:', f1)
# 打印结果:
res: <function f1 at 0x0000019F13E7D268>
f1: <function f1 at 0x0000019F13E7D268>
Earth element as a container
def f1():
print('from f1')
lt = [f1, 12, 3, 4, 5]
lt[0]()
Small exercises
def pay():
print('支付1e成功')
def withdraw():
print('提现2e成功')
dic = {
'1': pay,
'2': withdraw
}
while True:
msg = '''
'1': 支付,
'2': 提现,
'3': 退出,
'''
print(msg)
choice = input('>>: ').strip()
if choice == '3':
break
elif choice in dic:
dic[choice]()
Nested functions
Function inside nested functions
def f1():
print('from f1')
def f2():
print('from f2')
f2()
f1()
Namespace and scope
Namespaces
Built-in namespace
A built-in method of storage space
Built-in data type method; Python interpreter own method (print / len / list / str / dict)
Global name space
In addition to the built-in global and local call
The local name space
Local call within the function definitions
Namespace order of execution (generated)
- Built-in namespace: python interpreter starts when there is a
- Global name space: time code executable file will have a global
- The local name space: time function call will have a local
Search Order
From the current position to find, can not find in that order, not looking backward: Local> Global> Built-in> error
Scope
Global scope
Built-in namespace + global namespace -> global scope
Local scope
Local namespace -> local scope
- Global scope and local scope x x no relationship
- Local scope x 1 x 2 and the local scope is nothing, even if a local scope and local scope 2 in the same local scope
global keyword
x = 10
def func():
global x
x = 20
func()
print(x) # 打印20
nonlocal keyword
x = 10
def f1():
x = 2
def f2():
nonlocal x # nonlocal让x成为额顶层函数的局部,不是让它成为全局
x = 30
f2()
print(x)
f1()
# 打印30
important point
All variable data types can break all the rules above
lt = [10]
def f1():
lt.append(20)
f1()
print(lt)
# 打印结果:
[10,20]