Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

python - 装饰器作为类的限制与装饰器作为函数的限制(Limit of decorator as class compared to decorator as function)

I want to make sure that I understood correctly how decorator as class works.

(我想确保我正确理解装饰器作为类的工作方式。)

Let's say i have a decorator as a function that add an attribute to an object

(假设我有一个装饰器作为向对象添加属性的函数)

def addx(obj):
    obj.x = 10
    return obj

@addx
class A:
    pass

assert A.x == 10

Is it possible to write the same decorator as a class decorator?

(是否可以编写与类装饰器相同的装饰器?)

since the class decorator can't return the object itself with __init__

(因为类装饰器无法使用__init__返回对象本身)

class addx:
    def __init__(self, obj):
        obj.x = 10
        # ???
  ask by Nazime Lakehal translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could write an equivalent class-based decorator like this...

(您可以像这样编写等效的基于类的装饰器...)

class addx:
    def __new__(self, obj):
        obj.x = 10
        return obj

@addx
class A:
    pass

assert A.x == 10

...but I don't think this really gets you anything.

(...但是我认为这真的不能给您带来任何好处。)

The utility of a class-based decorator becomes more apparent when your goal is to modify objects of class A , rather than class A itself.

(当您的目标是修改class A对象而不是class A本身的对象时,基于类的装饰器的实用程序将变得更加明显。)

Compare the following two decorators, one function based and one class based:

(比较以下两个修饰符,一个基于函数,一个基于类:)

def addx_func(kls):
    def wrapper():
        res = kls()
        res.x = 10
        return res

    return wrapper


class addx_class:
    def __init__(self, kls):
        self.kls = kls

    def __call__(self):
        res = self.kls()
        res.x = 10
        return res


@addx_func
class A:
    pass


@addx_class
class B:
    pass


a = A()
assert a.x == 10

b = B()
assert b.x == 10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...