来自decorator,调用decorator的模块的访问范围

时间:2017-03-22 19:10:06

标签: python scope python-decorators

我在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模块的本地或全局范围?

1 个答案:

答案 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'>