1. 访问外部函数变量
内部函数可以直接读取外部函数中的变量:
def outer():
message = "Hello from outer!" # 外部函数变量
def inner():
print(message) # 内部函数访问外部变量
inner()
outer() # 输出: Hello from outer!
掌握函数作用域与闭包的核心概念
在Python中,函数可以定义在其他函数内部,形成函数嵌套结构。这种结构中,内部函数可以访问外部函数的变量,这种变量称为嵌套变量或非局部变量。
理解嵌套变量的关键在于掌握Python的变量作用域规则:
内部函数可以直接读取外部函数中的变量:
def outer():
message = "Hello from outer!" # 外部函数变量
def inner():
print(message) # 内部函数访问外部变量
inner()
outer() # 输出: Hello from outer!
当需要修改外部函数变量时,需要使用nonlocal关键字:
def counter():
count = 0
def increment():
nonlocal count # 声明为非局部变量
count += 1
return count
return increment
c = counter()
print(c()) # 输出: 1
print(c()) # 输出: 2
print(c()) # 输出: 3
嵌套函数可以创建闭包,保留外部函数的状态:
def power_factory(exponent):
# 外部函数接收参数
def power(base):
# 内部函数使用外部函数的变量
return base ** exponent
return power
# 创建平方函数
square = power_factory(2)
print(square(3)) # 输出: 9
print(square(4)) # 输出: 16
# 创建立方函数
cube = power_factory(3)
print(cube(2)) # 输出: 8
print(cube(3)) # 输出: 27
函数嵌套是实现装饰器的核心机制:
def logger(func):
# 外部函数接收函数作为参数
def wrapper(*args, **kwargs):
print(f"调用函数: {func.__name__}")
result = func(*args, **kwargs)
print(f"函数 {func.__name__} 执行完毕")
return result
return wrapper
@logger
def add(a, b):
return a + b
print(add(3, 5))
# 输出:
# 调用函数: add
# 函数 add 执行完毕
# 8
使用嵌套变量创建有记忆的函数:
def create_account(initial_balance):
balance = initial_balance
def deposit(amount):
nonlocal balance
balance += amount
return balance
def withdraw(amount):
nonlocal balance
if amount > balance:
return "余额不足"
balance -= amount
return balance
def get_balance():
return balance
return {'deposit': deposit, 'withdraw': withdraw, 'get_balance': get_balance}
# 使用示例
account = create_account(1000)
print(account['get_balance']()) # 1000
print(account['deposit'](500)) # 1500
print(account['withdraw'](200)) # 1300
print(account['get_balance']()) # 1300
nonlocal用于修改嵌套作用域中的变量global用于修改全局作用域中的变量掌握LEGB规则
修改嵌套作用域变量
状态保持与封装
Python高级特性
本文由JiangTe于2025-08-05发表在吾爱品聚,如有疑问,请联系我们。
本文链接:http://521pj.cn/20257369.html
发表评论