Python函数对象、嵌套和作用域总结
函数对象
函数在Python中是第一类对象,可以像普通变量一样使用。
1. 赋值给变量
def greet(name):
return f"Hello, {name}!"say_hello = greet# 将函数赋值给变量
print(say_hello("Alice"))# 输出: Hello, Alice!
2. 作为容器元素
def add(a, b):
return a + bdef subtract(a, b):
return a - boperations = [add, subtract]
print(operations[0](5, 3))# 输出: 8
print(operations[1](5, 3))# 输出: 2
3. 作为函数参数
def apply(func, x, y):
return func(x, y)def multiply(a, b):
return a * bprint(apply(multiply, 4, 5))# 输出: 20
4. 作为函数返回值
def create_power_function(exponent):
def power(base):
return base ** exponent
return powersquare = create_power_function(2)
cube = create_power_function(3)
print(square(4))# 输出: 16
print(cube(4))# 输出: 64
函数嵌套
def outer():
x = 10def inner():
print(f"x is {x}")# 内部函数可以访问外部函数的变量inner()# 在外部函数中调用内部函数outer()# 输出: x is 10
# inner()# 这会报错,外部无法直接访问内部函数
名称空间和作用域
1. 名称空间示例
# 全局名称空间
global_var = "I'm global"def my_function():
# 局部名称空间
local_var = "I'm local"
print(local_var)
print(global_var)# 可以访问全局变量my_function()
# print(local_var)# 这会报错,无法访问局部变量
2. 查找顺序示例
def test():
# len = "local len"# 如果取消注释,会覆盖内置len
print(len("hello"))# 查找顺序: 局部 -> 全局 -> 内置test()# 输出: 5
3. global关键字
count = 0def increment():
global count# 声明使用全局变量
count += 1increment()
print(count)# 输出: 1
4. nonlocal关键字
def outer():
x = "outer"def inner():
nonlocal x# 声明使用外层函数的变量
x = "inner"
print("Inner:", x)inner()
print("Outer:", x)outer()
# 输出:
# Inner: inner
# Outer: inner
5. 修改内置名称空间
# 修改全局名称空间中的内置函数
original_len = len# 保存原始len函数def my_len(obj):
return original_len(obj) * 2len = my_len# 覆盖内置len函数print(len("hi"))# 输出: 4 (原始长度2 * 2)