【问题标题】:From decorator, access scope of module in which decorator is invoked从装饰器,调用装饰器的模块的访问范围
【发布时间】:2017-08-15 02:22:28
【问题描述】:

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

【问题讨论】:

  • 为什么要访问该范围?如果您需要访问to_belong_to_newly_created_class,那就是func。您已经可以访问它了。 - 编辑:等等,不,你定义的参数错误。但是,如果您正确定义了参数,您可以访问它作为装饰器的参数。
  • 我是否可以访问装饰器内部的self(指Example的实例)?如果我这样做,我如何访问它?
  • 装饰器执行时没有Example的实例。
  • 这个装饰器实际上应该做什么? CreatedClass的作用是什么? CreatedClass 的定义应该在什么时候执行,CreatedClass 定义后会发生什么?你的装饰器没有多大意义,你也没有对它应该做什么给出太多解释,所以很难说它应该是什么样子。
  • to_belong_to_newly_created_class 方法应该是Example 的方法、CreatedClass 的方法还是其他什么? CreatedClass 是否应该可以通过Example 的属性访问?还是to_belong_to_newly_created_class 应该是创建CreatedClass 实例的方法?目前还不清楚这一切的预期结果是什么。

标签: python scope python-decorators


【解决方案1】:
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'>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多