如何在当前模块上调用setattr()? [英] How do I call setattr() on the current module?
问题描述
作为第一个参数 object
传递给函数 setattr(object,name,value)
,在当前模块上设置变量?
例如:
setattr(object,SOME_CONSTANT,42);
效果如下:
<$ p包含这些行的模块中的$ p>
SOME_CONSTANT = 42
正确的 object
)。
我在模块级动态地生成了几个值,在模块级别定义 __ getattr __
,这是我的后备。
import sys
thismodule = sys.modules [__ name__]
setattr(thismodule,name,value)
或者不使用 setattr
(它打破问题的字母,但满足 - ):
pre code $ globals()[name] = value
注意:在模块范围内,后者相当于:
vars()[name] = value
其中是更简洁一点,但不起作用从一个函数中( vars()
)给出了调用范围的变量:在全局范围调用时的模块变量,然后使用它的R / W ,但函数的变量在函数中调用时,必须将其视为R / O - Python在线文档可能会对这种特定的区别有点混淆)。
What do I pass as the first parameter "object
" to the function setattr(object, name, value)
, to set variables on the current module?
For example:
setattr(object, "SOME_CONSTANT", 42);
giving the same effect as:
SOME_CONSTANT = 42
within the module containing these lines (with the correct object
).
I'm generate several values at the module level dynamically, and as I can't define __getattr__
at the module level, this is my fallback.
import sys
thismodule = sys.modules[__name__]
setattr(thismodule, name, value)
or, without using setattr
(which breaks the letter of the question but satisfies the same practical purposes;-):
globals()[name] = value
Note: at module scope, the latter is equivalent to:
vars()[name] = value
which is a bit more concise, but doesn't work from within a function (vars()
gives the variables of the scope it's called at: the module's variables when called at global scope, and then it's OK to use it R/W, but the function's variables when called in a function, and then it must be treated as R/O -- the Python online docs can be a bit confusing about this specific distinction).
这篇关于如何在当前模块上调用setattr()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!