简体   繁体   English

装饰器在调用之前注册功能

[英]Decorators to register functions before being called

I would like to decorate bar and baz to register them with Container and collect the callback in Foo . 我想装饰barbaz以将它们注册到Container并在Foo收集回调。 Is this possible given python decorators? 是否可以使用python装饰器?

class Foo(object):
    results = []
    def __init__(self, app):
        self.app = app
        self.registerAll()

    def registerAll(self):
        self.results.append(self.app.myRegister(self.baz))
        self.results.append(self.app.myRegister(self.bar))

    def baz(self):
        print("baz")

    def bar(self):
        print("bar")

class Container(object):
    funcs = []

    def start(self):
        self.f = Foo(self)

    def myRegister(self, f):
        self.funcs.append(f)
        print("myRegister")
        def callback(res):
            print('cb')
        return callback

x = Container()
x.start()

Your question looks suspiciously like an XY Problem , since it's very unclear what you ultimately hope to accomplish by registering the functions (which are actually class methods). 您的问题看起来像一个XY问题 ,因为它不清楚,您最终希望通过注册功能(实际上是类方法)来完成什么。 (Also see What is the XY problem? ) Nevertheless, here's one way to do what you want — assuming I understand what you have so far in your question. (另请参见XY问题是什么? )不过,这是您想要做的一种方法-假设我了解您到目前为止所遇到的问题。

I made Container.myRegister() a classmethod since it only references an attribute of the class it is in. I also defined the Container class before the Foo class so the former could be referenced by the decorator. 我将Container.myRegister() classmethod因为它仅引用了其所在类的属性。我还在Foo类之前定义了Container类,因此前者可以由装饰器引用。 In addition I removed the registerAll() method, since it's no longer needed (however that means the class attribute results is now not referenced anywhere, so maybe it should be removed, too...). 另外,我删除了registerAll()方法,因为不再需要它(但是这意味着类属性results现在没有在任何地方引用,因此也许也应该删除它)。

class Container(object):
    funcs = []

    def start(self):
        self.f = Foo(self)

    @classmethod
    def myRegister(cls, f):
        cls.funcs.append(f)
        print("myRegister")
        def callback(res):
            print('cb')
        return callback

def decorate(cls):
    def decorator(method):
        cls.myRegister(method)
        return method
    return decorator

class Foo(object):
    results = []

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

    @decorate(Container)
    def baz(self):
        print("baz")

    @decorate(Container)
    def bar(self):
        print("bar")

x = Container()
x.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM