DAY11 函数对象 函数的嵌套 名称空间和作用域 作用域修改关键字
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 + b
def subtract(a, b):
return a - b
operations = [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 * b
print(apply(multiply, 4, 5))# 输出: 20
4. 作为函数返回值
def create_power_function(exponent):
def power(base):
return base ** exponent
return power
square = create_power_function(2)
cube = create_power_function(3)
print(square(4))# 输出: 16
print(cube(4))# 输出: 64
函数嵌套
def outer():
x = 10
def 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 = 0
def increment():
global count# 声明使用全局变量
count += 1
increment()
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) * 2
len = my_len# 覆盖内置len函数
print(len("hi"))# 输出: 4 (原始长度2 * 2)

浙公网安备 33010602011771号