在Python中实现装饰器描述符的最佳方法是什么?

时间:2020-03-22 16:45:16

标签: python python-decorators python-descriptors

假设我要实现一个装饰器,该装饰器应可用于函数,静态方法,类方法或常规方法:

class decorator:

    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)


class C:

    @decorator
    def f(self, x):
        print(x)

    @decorator
    @classmethod
    def h(cls, x):
        print(x)


@decorator
def g(x):
    print(x)

c = C()
c.f(1)  # Fails.
g(2)  # Works.
C.h(3)  # Fails.

我能想到的最好的方法是:

class decorator:

    def __get__(self, instance, owner):
        return type(self.f).__get__(self.f, instance, owner)

我想知道这是否是实现描述符的正确方法?我是否应该类似地实现__del____set__

0 个答案:

没有答案