如何在当前模块上调用

如何在当前模块上调用

本文介绍了如何在当前模块上调用 setattr()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该将什么作为第一个参数object"传递给函数setattr(object, name, value),以在当前模块上设置变量?>

例如:

setattr(object, "SOME_CONSTANT", 42);

产生与以下相同的效果:

SOME_CONSTANT = 42

在包含这些行的模块中(使用正确的object).

我在模块级别动态生成多个值,由于我无法在模块级别定义 __getattr__,这是我的后备方案.

解决方案
import systhismodule = sys.modules[__name__]setattr(thismodule, name, value)

或者,不使用 setattr(它打破了问题的字母但满足相同的实际目的;-):

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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:33