python装饰器

装饰器是一种特殊类型的函数,它可以用来修改其他函数的行为。在Python中,装饰器是一个接受函数作为参数并返回一个新函数的函数,这个新函数通常会包含原函数的一些额外功能。

1. 函数装饰器

这是最常见的装饰器类型,它接受一个函数作为参数,并返回一个新的函数。这种装饰器可以用来修改被装饰函数的行为,或者在被装饰函数前后添加额外的功能。

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_decorator
def say_hello():
    print("Hello!")

say_hello()

my_decorator是一个函数装饰器,它接受一个函数func作为参数,并返回一个新的函数wrapper。

wrapper函数在调用func之前和之后添加了一些额外的行为。当我们使用@my_decorator语法糖来装饰say_hello函数时,实际上是将say_hello函数传递给my_decorator,然后将返回的wrapper函数赋值给say_hello。

因此,当我们调用say_hello()时,实际上是在调用wrapper(),从而实现了在原函数前后添加额外功能的目的。

扫一扫欢迎关注,一起学习!

2. 类装饰器

这种装饰器接受一个类作为参数,并返回一个新的类。类装饰器可以用来修改被装饰类的行为,或者在被装饰类前后添加额外的功能。

def my_decorator(cls):
    class Wrapper:
        def __init__(self, *args, **kwargs):
            self.wrapped = cls(*args, **kwargs)

        def __getattr__(self, name):
            return getattr(self.wrapped, name)

    return Wrapper

@my_decorator
class MyClass:
    def __init__(self, x):
        self.x = x

    def print_x(self):
        print(self.x)

obj = MyClass(10)
obj.print_x()  # 输出:10

my_decorator是一个类装饰器,它接受一个类cls作为参数,并返回一个新的类Wrapper。

Wrapper类在初始化时接收任意数量的参数和关键字参数,并将它们传递给原始类cls的构造函数。然后,Wrapper类重写了__getattr__方法,使其在访问原始类的属性时被代理给原始类的实例。

当我们使用@my_decorator语法来装饰MyClass类时,实际上是将MyClass类传递给my_decorator,然后将返回的Wrapper类赋值给MyClass。

因此,当我们创建MyClass的实例并调用其方法时,实际上是在调用Wrapper类的实例的方法,从而实现了在原类前后添加额外功能的目的。

3. 方法装饰器

这种装饰器接受一个方法作为参数,并返回一个新的方法。方法装饰器通常用来修改被装饰方法的行为,或者在被装饰方法前后添加额外的功能。

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper

class MyClass:
    @my_decorator
    def my_method(self, x):
        print("The value of x is:", x)

obj = MyClass()
obj.my_method(10)

my_decorator是一个方法装饰器,它接受一个方法func作为参数,并返回一个新的方法wrapper。wrapper方法在调用func之前和之后添加了一些额外的行为。

当我们使用@my_decorator语法糖来装饰MyClass类的my_method方法时,实际上是将my_method方法传递给my_decorator,然后将返回的wrapper方法赋值给my_method。

因此,当我们调用obj.my_method(10)时,实际上是在调用wrapper方法,从而实现了在原方法前后添加额外功能的目的。

4. 内置装饰器

Python提供了一些内置的装饰器,如@property、@staticmethod和@classmethod等。这些装饰器可以直接应用到函数或方法上,以改变其行为或特性。

具体可以参考面向对象一节。

class People:

    @staticmethod
    def hello_word():
        print('hello world')


People.hello_word()
class People:
    __name = '小明'

    @classmethod
    def hello(cls):
        print(cls.__name)



People.hello()

class People:

    @property
    def hello_1(self):
        return 'hello'

	@property
    def hello_2(self):
        return self.__name


p = People()
print(p.hello_1)
print(p.hello_2)

5. 装饰器工厂

这是一种创建装饰器的高阶函数。它接受一些参数,然后返回一个装饰器。这种装饰器可以用来根据不同的参数创建具有不同行为的装饰器。

def my_decorator_factory(prefix):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f"{prefix}: Before function call")
            result = func(*args, **kwargs)
            print(f"{prefix}: After function call")
            return result
        return wrapper
    return decorator

@my_decorator_factory("INFO")
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Alice")

#########输出######
INFO: Before function call
Hello, Alice!
INFO: After function call

my_decorator_factory是一个装饰器工厂,它接受一个参数prefix。这个工厂返回一个新的装饰器decorator,该装饰器接受一个函数func作为参数,并返回一个新的函数wrapper。wrapper函数在调用func之前和之后添加了带有prefix前缀的打印语句。

当我们使用@my_decorator_factory("INFO")语法来装饰say_hello函数时,实际上是将"INFO"传递给my_decorator_factory,然后将返回的decorator应用于say_hello。

  • 21
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值