如何在当前模块上调用 setattr() ?
我应该将什么作为第一个参数“object
”传递给函数setattr(object, name, value)
,以在当前模块上设置变量?
例如:
setattr(object, "SOME_CONSTANT", 42);
给出与以下相同的效果:
SOME_CONSTANT = 42
在包含这些行的模块内(使用正确的对象
)。
我在模块级别动态生成多个值,并且由于我无法在模块级别定义 __getattr__ ,所以这是我的后备方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者,不使用
setattr
(这破坏了问题的字母,但满足相同的实际目的;-):注意:在模块范围内,后者相当于
:更简洁一点,但不能在函数内工作(
vars()
给出调用范围的变量:在全局范围调用时模块的变量,然后就可以了使用 R/W,但在函数中调用函数的变量时,必须将其视为 R/O ——Python 在线文档对于这种具体区别可能有点令人困惑)。or, without using
setattr
(which breaks the letter of the question but satisfies the same practical purposes;-):Note: at module scope, the latter is equivalent to:
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).在Python 3.7中,您将能够在模块级别使用
__getattr__
(相关答案)。根据 PEP 562:
In Python 3.7, you will be able to use
__getattr__
at the module level (related answer).Per PEP 562:
如果必须在模块内设置模块作用域变量,那么
global
有什么问题吗?因此:
If you must set module scoped variables from within the module, what's wrong with
global
?thus:
globals()["SOME_CONSTANT"] = 42
但globals()["SOME_CONSTANT"] = 42