摘要:def my_decorator(func): def wrapper(*args, **kwargs): print("Before call") result = func(*args, **kwargs) print("After call") retu
创建一个简单的装饰器来包装一个函数:
def my_decorator(func): def wrapper: print("Something is happening before the function is called.") func print("Something is happening after the function is called.") return wrapper@my_decoratordef say_hello: print("Hello!")say_hello将参数传递给装饰器内的函数:
def my_decorator(func): def wrapper(*args, **kwargs): print("Before call") result = func(*args, **kwargs) print("After call") return result return wrapper@my_decoratordef greet(name): print(f"Hello {name}")greet("Alice")为了保留原始函数的元数据在装饰时:
from functools import wrapsdef my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): """Wrapper function""" return func(*args, **kwargs) return wrapper@my_decoratordef greet(name): """Greet someone""" print(f"Hello {name}")print(greet.__name__) # Outputs: 'greet'print(greet.__doc__) # Outputs: 'Greet someone'创建一个使用类的装饰器:
class MyDecorator: def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print("Before call") self.func(*args, **kwargs) print("After call")@MyDecoratordef greet(name): print(f"Hello {name}")greet("Alice")创建一个接受自身参数的装饰器:
def repeat(times): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(times): func(*args, **kwargs) return wrapper return decorator@repeat(3)def say_hello: print("Hello")say_hello将装饰器应用于类中的方法:
def method_decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): print("Method Decorator") return func(self, *args, **kwargs) return wrapperclass MyClass: @method_decorator def greet(self, name): print(f"Hello {name}")obj = MyClassobj.greet("Alice")def smart_decorator(arg=None): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if arg: print(f"Argument: {arg}") return func(*args, **kwargs) return wrapper if callable(arg): return decorator(arg) return decorator@smart_decoratordef no_args: print("No args")@smart_decorator("With args")def with_args: print("With args")no_argswith_argsclass MyClass: @classmethod @my_decorator def class_method(cls): print("Class method called")MyClass.class_methodclass MyClass: @staticmethod @my_decorator def static_method: print("Static method called")MyClass.static_method来源:自由坦荡的湖泊AI
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!