简体   繁体   English

什么是setattr()用于模块的pythonic方法?

[英]What is the pythonic way to setattr() for a module?

In a class method, I can add attributes using the built-in function: 在类方法中,我可以使用内置函数添加属性:

setattr(self, "var_name", value).  

If I want to do the same thing within a module, I can do something like: 如果我想在模块中做同样的事情,我可以做类似的事情:

globals()["var_name"] = value

Is this the best way to do this, or is there a more pythonic solution? 这是最好的方法吗,还是有更多的pythonic解决方案?

Your suggested approach 你建议的方法

globals()["var_name"] = value

is indeed the most Pythonic way. 确实是最恐怖的方式。 In particular, it's significantly more Pythonic than using eval , which would be your main (though not only) alternative. 特别是,它比使用eval更加Pythonic,这将是你的主要(但不仅仅是)替代方案。

However, if you still want to use setattr , you may do so by using sys.modules to get a reference to the current module object with the current module's __name__ variable ( explained here ) as follows: 但是,如果您仍想使用setattr ,则可以使用sys.modules来获取对当前模块对象的引用,其中包含当前模块的__name__变量( 在此处说明 ),如下所示:

import sys
setattr(sys.modules[__name__], "var_name", value)

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

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