·

Python 是一种高级通用语言,支持类作为其内置面向对象编程 (OOP) 范例的一部分。有时,在使用 Python 的变量时,可能希望隐藏变量,而不创建额外的类来维护代码。此外,可能希望向函数添加少量功能,而不生成另一个不必要的函数。在这种情况下,用于函数修改的装饰器和用于变量隐藏的闭包可以作为修复应用。
闭 包:
虽然不在内存中,但 closure 是一个函数对象,它记住封闭作用域中的值。当嵌套函数引用其封闭作用域中的变量时,将产生闭包。尽管封闭范围不再处于活动状态,但闭包会“关闭”它引用的变量,从而保留它们的值。函数调用之间的数据封装和状态保留通常通过闭包完成。
装饰:
装饰器是一种在不改变其源代码的情况下改变函数或类的行为的方法。它允许一个人用另一个函数或类包装一个现有的函数或类,从而增强它的能力。包括 logging、timing、input validation、authentication 等项目通常需要装饰器。它们提供了一种确定问题优先级并保持代码模块化和可重用性的方法。
一个基本的闭包示例
简单地说,即使在外部函数完成后,闭包也是一种从周围环境中记住和访问变量值的工具。
def outer_function(x): def inner_function(y): return x + y return inner_functionclosure = outer_function(5)print(closure(3)) # Output: 8在给定的示例中,“outer_function”使用输入“x”定义一个名为“inner_function”的内部函数,该输入接受另一个参数“y”,因此生成“x”和“y”之和。然后,内部函数 “inner_function” 由 “outer_function” 返回。作为嵌套函数,“inner_function” 可以访问 “outer_function” 的封闭范围内的变量,在这种情况下,使用 “x”。
为什么以及如何使用闭包?
Python 中的数据隐藏是闭包的使用——即在外部函数中定义变量,随后在内部函数中应用。这有助于捕获数据,并在函数修改之外停止发生。
class SecureData: def __init__(self, data): self.data = data self.password = 'secret' def get_data(self, passwd): if passwd == self.password: return self.data else: return Nonesecure_data = SecureData('my sensitive data')print(secure_data.get_data('secret')) # Output: 'my sensitive data'print(secure_data.get_data('wrong password')) # Output: None两个实例变量 — data 和 password — 首先在 SecureData 类的 __init__ 函数中建立。
在 SecureData 类中定义,get_data 函数接受密码作为参数。它将给定的 password 与类的 password 实例变量相关联。如果它们适合,则返回 data 实例变量。否则,它将返回 None。
生成 SecureData 类的实例 (secure_data) 以获取安全数据。之后,将密码作为参数传递,您可以在 secure_data 实例上执行 get_data 函数。
def create_secure_data(data): password = 'secret' def get_data(passwd): if passwd == password: return data else: return None return get_datasecure_data = create_secure_data('my sensitive data')# Now, the 'secure_data' variable contains a reference to # the inner function 'get_data' which can access the 'password' # and 'data' variables of the outer function 'create_secure_data'.# To retrieve the secure data, you need to call the 'secure_data' # function with the correct password.print(secure_data('secret')) # Output: 'my sensitive data'print(secure_data('wrong password'))什么是装饰器
装饰器是一个高阶函数,它将另一个函数作为参数,为其添加一些功能,并生成一个无需修改源代码的新函数。装饰器将对象封装在另一个函数中,因此可以单独或一般地改变它们的行为。这是一个例子:
def decorator_function(func): def wrapper_function(): print("Before function is called.") func() print("After function is called.") return wrapper_function@decorator_functiondef hello(): print("Hello, world!")hello()深入研究 装饰器
Python 中的装饰器允许元编程,这是一种代码可以在运行时或编译时与其他代码交互的编程。然后,装饰器提供了一种机制来更改函数或类的行为,而无需更改其源代码,因此说明了一种元编程技术。
def debug(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__} with args: {args}, \ kwargs: {kwargs}") result = func(*args, **kwargs) print(f"{func.__name__} returned: {result}") return result return wrapper@debugdef add(a, b): return a + bresult = add(3, 5)print(result)