admin管理员组文章数量:1355600
I am trying to create a decorator which enables me to register callback functions to an instance of ClassB
. I would like to use this decorator in other classes within my program (eg. ClassA
) but want to instantiate ClassB
as an instance variable of ClassA
instead of instantiating it as a module level variable. When instantiating at module level everything works fine, however when instantiating as an instance variable of ClassA
it fails.
class ClassB():
def __init__(self):
self.callbacks = []
def register_callback(self):
def wrapper(fn):
self.callbacks.append(fn)
return fn
return wrapper
Instantiating at module level works well:
import ClassB
class_b = ClassB()
class ClassA():
def __init__(self):
pass
@class_b.register_callback()
def do_something(self):
# do stuff
Instantiating as an instance variable does not work:
import ClassB
class ClassA():
def __init__(self):
self.class_b = SomeClassB()
@self.class_b.register_callback()
def do_something(self):
# do stuff
What is the correct syntax/ way to achieve what I am trying to do?
本文标签:
版权声明:本文标题:Using python decorators associated with an instance level object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743962212a2569237.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论