py来定义全局变量吗

py来定义全局变量吗

本文介绍了我可以使用__init__.py来定义全局变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个应该在包的所有子模块中可用的常量。我认为最好的地方应该在根包的 __ init __。py 文件中。但我不知道该怎么做。假设我有几个子包,每个包都有几个模块。我怎样才能从这些模块访问该变量?



当然,如果这是完全错误的,并且有更好的选择,我想知道它。 / p>

解决方案

您应该可以将它们放在 __ init __。py 中。这是完成的。

mypackage / __ init __。py

p>

  MY_CONSTANT = 42 



c $ c> from mypackage import MY_CONSTANT
printmy constant is,MY_CONSTANT

然后,import mymodule:

 >>> from mypackage import mymodule 
我的常量是42

如果你有常量,将它们放在一个单独的模块(constants.py,config.py,...)中是合理的(最佳实践),然后如果你希望它们在包名称空间中,请导入它们。



> mypackage / __ init __。py

  from mypackage.constants import * 

但是,这并不会自动在程序包模块的名称空间中包含常量。包中的每个模块都必须显式地从 mypackage 或 mypackage.constants 中


I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the __init__.py file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules?

Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.

解决方案

You should be able to put them in __init__.py. This is done all the time.

mypackage/__init__.py:

MY_CONSTANT = 42

mypackage/mymodule.py:

from mypackage import MY_CONSTANT
print "my constant is", MY_CONSTANT

Then, import mymodule:

>>> from mypackage import mymodule
my constant is 42

Still, if you do have constants, it would be reasonable (best practices, probably) to put them in a separate module (constants.py, config.py, ...) and then if you want them in the package namespace, import them.

mypackage/__init__.py:

from mypackage.constants import *

Still, this doesn't automatically include the constants in the namespaces of the package modules. Each of the modules in the package will still have to import constants explicitly either from mypackage or from mypackage.constants.

这篇关于我可以使用__init__.py来定义全局变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:00