简体   繁体   English

python对象上方的命名空间层次结构

[英]python namespace hierarchy above object

For example, if this code were contained in a module called some_module 例如,如果此代码包含在名为some_module的模块中

class C:
    class C2:
        def g(self):
            @printNamespaceAbove
            def f():
                pass

then printNamespaceAbove would be defined so that this code would output something like 然后将定义printNamespaceAbove,以便此代码将输出类似

[some_module,C,C2,g]

There is no way to make this code, as presented, have any output -- the body of g (including the decorator you'd like to do the printing) simply DOESN'T execute until g is called. 有没有办法让这个代码,提交,有任何输出-克的身体(包括你想要做印刷装饰)根本执行,直到G称为。 I assume you do not literally intend for "this code" on its own to output anything, but rather intend to add a call such as C.C2().g() [which will actually do the output]. 我假设您实际上并不打算单独使用“此代码”来输出任何内容,而是打算添加诸如C.C2()。g()之类的调用[实际上将执行输出]。

There's not really a very efficient way to do this -- you (well, the decorator;-) must start at the module level (which you can identify through the globals of f , the decorator's argument: its name is f.func_globals['__name__'] and via its name you can look it up in sys.modules ), then you must walk down every possible chain of names until you locate your calling function (eg via the inspect module in the standard library). 确实没有一种非常有效的方法-您(好,装饰器;-)必须从模块级别开始(您可以通过装饰器参数f的全局变量来识别它:它的名称为f.func_globals['__name__']并通过其名称可以在sys.modules查找它,然后必须遍历所有可能的名称链,直到找到调用函数为止(例如,通过标准库中的inspect模块)。 Note also that nested functions are a particular headache in several corner cases. 还要注意,嵌套函数在某些特殊情况下尤其令人头疼。

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

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