将一长串常量导入到 Python 文件中
在Python中,是否有类似的C
预处理器语句,例如?:
#define MY_CONSTANT 50
另外,我有一个要导入的大量常量列表几节课。是否有类似的情况,即在 .py 文件中将常量声明为一长串语句,然后将其导入到另一个 .py 文件中?
编辑。
文件 Constants.py
内容为:
#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""
MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51
且 myExample.py
内容为:
#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""
import sys
import os
import Constants
class myExample:
def __init__(self):
self.someValueOne = Constants.MY_CONSTANT_ONE + 1
self.someValueTwo = Constants.MY_CONSTANT_TWO + 1
if __name__ == '__main__':
x = MyClass()
编辑。
从编译器来看,
名称错误:“全局名称 “MY_CONSTANT_ONE”未定义”
myExample 中的函数 init 行 13 self.someValueOne = Constants.MY_CONSTANT_ONE + 1 份 输出 程序退出,代码为 #1 0.06 秒后。
In Python, is there an analogue of the C
preprocessor statement such as?:
#define MY_CONSTANT 50
Also, I have a large list of constants I'd like to import to several classes. Is there an analogue of declaring the constants as a long sequence of statements like the above in a .py
file and importing it to another .py
file?
Edit.
The file Constants.py
reads:
#!/usr/bin/env python
# encoding: utf-8
"""
Constants.py
"""
MY_CONSTANT_ONE = 50
MY_CONSTANT_TWO = 51
And myExample.py
reads:
#!/usr/bin/env python
# encoding: utf-8
"""
myExample.py
"""
import sys
import os
import Constants
class myExample:
def __init__(self):
self.someValueOne = Constants.MY_CONSTANT_ONE + 1
self.someValueTwo = Constants.MY_CONSTANT_TWO + 1
if __name__ == '__main__':
x = MyClass()
Edit.
From the compiler,
NameError: "global name
'MY_CONSTANT_ONE' is not defined"function init in myExample at line
13 self.someValueOne =
Constants.MY_CONSTANT_ONE + 1 copy
output Program exited with code #1
after 0.06 seconds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
Python 没有经过预处理。您只需创建一个文件
myconstants.py
:然后导入它们即可:
Python isn't preprocessed. You can just create a file
myconstants.py
:And importing them will just work:
Python没有预处理器,也没有常量,因为它们不能被改变——你总是可以改变(几乎,你可以模拟常量对象属性,但是为了常量而这样做的情况很少见)已完成但不被认为有用)一切。当定义一个常量时,我们定义一个大写加下划线的名字,然后就到此为止了——“我们都是同意的成年人”,没有一个理智的人会改变一个常量。当然,除非他有很好的理由并且确切地知道他在做什么,在这种情况下你不能(而且可能不应该)以任何方式阻止他。
但是当然,您可以定义带有值的模块级名称并在另一个模块中使用它。这不是特定于常量或任何东西,请在模块系统上阅读。
Python doesn't have a preprocessor, nor does it have constants in the sense that they can't be changed - you can always change (nearly, you can emulate constant object properties, but doing this for the sake of constant-ness is rarely done and not considered useful) everything. When defining a constant, we define a name that's upper-case-with-underscores and call it a day - "We're all consenting adults here", no sane man would change a constant. Unless of course he has very good reasons and knows exactly what he's doing, in which case you can't (and propably shouldn't) stop him either way.
But of course you can define a module-level name with a value and use it in another module. This isn't specific to constants or anything, read up on the module system.
当然你可以这样做:
And ofcourse you can do:
当然,您可以将常量放入单独的模块中。例如:
const.py:
main.py:
注意上面声明的,
A
、B
和C
都是变量,即可以改变在运行时。Sure, you can put your constants into a separate module. For example:
const.py:
main.py:
Note that as declared above,
A
,B
andC
are variables, i.e. can be changed at run time.尝试查看使用“设置”模块创建常量?和我可以阻止修改 Python 中的对象吗?
另一个有用的链接:http://code.activestate.com/recipes/65207-constants-in-python/ 告诉我们以下选项:
因此您可以创建一个这样的类,然后从 contants.py 模块导入它。这将让您确保该值不会被更改、删除。
Try to look Create constants using a "settings" module? and Can I prevent modifying an object in Python?
Another one useful link: http://code.activestate.com/recipes/65207-constants-in-python/ tells us about the following option:
So you could create a class like this and then import it from you contants.py module. This will allow you to be sure that value would not be changed, deleted.
作为使用几个答案中描述的导入方法的替代方法,请查看 configparser 模块。
ConfigParser 类实现基本配置文件解析器语言,该语言提供与 Microsoft Windows INI 文件中类似的结构。您可以使用它来编写可由最终用户轻松定制的 Python 程序。
As an alternative to using the import approach described in several answers, have a look a the configparser module.
The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.
使用任意名称创建常量文件,如 my_constants.py
像这样声明常量
对于像这样访问代码导入文件中的常量
并访问常量值 -
create constant file with any name like my_constants.py
declare constant like that
For accessing constant in your code import file like that
and access the constant value as -
如果您确实想要常量,而不仅仅是看起来像常量的变量,那么标准方法是使用不可变字典。不幸的是它还没有内置,所以你必须使用第三方食谱(比如这个或那个)。
If you really want constants, not just variables looking like constants, the standard way to do it is to use immutable dictionaries. Unfortunately it's not built-in yet, so you have to use third party recipes (like this one or that one).
在商业软件中,常量经常会深埋在许多文件夹中。将以下解决方案与上述解决方案结合使用,以获得最佳效果。这是对我有用的语法:
In commercial software, the constant(s) will frequently be buried many folders deep. Use solution below in combination with above solutions for best results. Here's the syntax that worked for me:
在最近的版本中,它似乎有点挑剔。
顶部答案中的模式
Main.py
constants.py
在此处输入代码
token = "12345"失败。
相反,我必须从常量中导入单个变量。
主.py
In more recent editions, it seems a bit pickier.
the mode in the top answer
Main.py
constants.py
enter code here
token = "12345"failed.
Instead, I had to import individual variable from constants.
Main.py
constants.py 文件很好,但我遇到了一种情况,我宁愿将常量放在文件顶部。
类似的 Python 字典需要使用字符串键 dict['A'] 访问变量,但我需要具有与模块导入相同语法的内容。
(出于好奇,我正在处理 Google Collab
.ipynb
多个文件,每个文件都有不同的配置变量,并且您无法快速编辑导入的constants.py
来自 Collab,也不能直接导入另一个.ipynb
文件)您也可以创建一个经典的 Python
Class
,但这需要定义一个__init__
。A
constants.py
file is good, but I ran into a situation where I would rather had my constants on top of the file.A similar Python dict would need an access to the variable with a string key
dict['A']
, but I needed something with the same syntax as a module import.(For the curious, I was working on Google Collab
.ipynb
multiple files, with different configuration variables for each of them, and you can't edit quickly an importedconstants.py
from Collab, nor import directly another.ipynb
file. )You could also create a classic Python
Class
, but this needs to define a__init__
这是我的解决方案:
Asum 目录结构
param1.py
param2.py
somefile.py
main.py
运行 main.py
结果:
如您所见,您可以使用另一个包中的 const 。
希望这对其他人有帮助!
This is my solution:
Asum Directory structure
param1.py
param2.py
somefile.py
main.py
Run main.py
Result:
As you can see, you can use const from another package.
Hope this helps others!!