2019.08.09 learning finishing
Function object
Functions are first-class objects, i.e. function may be used as the data processing.
1. The four functions of the function object
1. references
x = 'hello nick'
y = x
f = func
print(f)
<function func at 0x10af72f28>
2. as a parameter passed to a function
len(x)
def foo(m):
m()
foo(func)
from func
3. The return value can be used as a function of
def foo(x):
return x
res = foo(func)
print(res)
res()
<function func at 0x10af72f28>
from func
4. The types of elements can be used as a container
l = [x]
function_list = [func]
function_list[0]()
from func
Nested functions
1. function nested definitions
Internal function defined functions can not be used inside a function defined in an external function.
def f1():
def f2():
print('from f2')
f2()
f1()
from f2
2. nested function calls
def max2(x, y):
if x > y:
return x
else:
return y
def max4(a, b, c, d):
res1 = max2(a, b)
res2 = max2(res1, c)
res3 = max2(res2, d)
return res3
print(max4(1, 2, 3, 4))
4
Namespace and scope
1. Name Space
Namespace (name spaces): In the memory management when that chapter, we said that to create a variable is actually opened up a new space in memory. But we've been avoiding storing variable names, in fact, there is room for a binding relationship between a variable name and variable memory storage in memory, and this space is called a namespace.
1.1 built-in namespace
Built-in namespace: Store Pyhton interpreter that comes with the name, such asint、float、len
Life cycle: when the interpreter started to take effect, fail when the interpreter is closed
1.2 global name space
Global namespace: In addition to the built-in and a local name, the rest are stored in the global namespace, such as the following codex、func、l、z
Life cycle: when the file is executed into effect, expire after file execution
x = 1
def func():
pass
l = [1, 2]
if 3 > 2:
if 4 > 3:
z = 3
1.3 The local name space
The local name space: the name of the function body for storing generated during a function call, such as the following codef2
Life Cycle: take effect during the function call when the file is executed, expire after the function execution
def f1():
def f2():
print('from f2')
f2()
f1()
2. Scope
Domain refers to a region, i.e. the region scope of action.
Global Scope: Global effective, global survival, and includes built-in namespace global name space.
2.1 global scope
# 全局作用域
x = 1
def bar():
print(x)
bar()
1
2.2 local scope
# 局部作用域
def f1():
def f2():
def f3():
print(x)
x = 2
f3()
f2()
f1()
2
2.3 Notes
# 作用域注意点
x = 1
def f1(): # 定义阶段x=1
print(x)
def f2():
x = 2
f1()
f2()
1
2.4 Application of scopes function object +
# 作用域应用
def f1():
def inner():
print('from inner')
return inner
f = f1() # 把局部定义的函数放在全局之中
def bar():
f()
bar()
from inner