我在my_decorators.py
中有一个装饰器模块正在创建类,我将这些装饰器导入Example.py
以用于Example
类的方法:
my_decorators.py
def my_decorator():
def inner_decorator(func):
class CreatedClass(object):
something = 'something'
return CreatedClass
return inner_decorator
Example.py
class Example(object):
# I WANT TO ACCESS THIS SCOPE IN THE DECORATOR
@my_decorator
to_belong_to_newly_created_class(self):
pass
有没有办法在单独的模块中访问装饰器内Example
类或Example.py
模块的本地或全局范围?
答案 0 :(得分:0)
def my_decorator(f):
def inner_decorator(self, *args, **kwargs):
print(self.TEST) # Access the required member from self.
class CreatedClass(object):
something = 'something'
return CreatedClass
return inner_decorator
class Example(object):
TEST = 'TEST!!'
# I WANT TO ACCESS THIS SCOPE IN THE DECORATOR
@my_decorator
def to_belong_to_newly_created_class(self):
pass
if __name__ == '__main__':
ex = Example()
print(ex.to_belong_to_newly_created_class())
<强>输出:强>
TEST!!
<class '__main__.my_decorator.<locals>.inner_decorator.<locals>.CreatedClass'>