将一长串常量导入到 Python 文件中

发布于 2024-11-15 11:53:37 字数 966 浏览 4 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

溺孤伤于心 2024-11-22 11:53:37

Python 没有经过预处理。您只需创建一个文件 myconstants.py

MY_CONSTANT = 50

然后导入它们即可:

import myconstants
print myconstants.MY_CONSTANT * 2

Python isn't preprocessed. You can just create a file myconstants.py:

MY_CONSTANT = 50

And importing them will just work:

import myconstants
print myconstants.MY_CONSTANT * 2
深爱成瘾 2024-11-22 11:53:37

Python没有预处理器,也没有常量,因为它们不能被改变——你总是可以改变(几乎,你可以模拟常量对象属性,但是为了常量而这样做的情况很少见)已完成但不被认为有用)一切。当定义一个常量时,我​​们定义一个大写加下划线的名字,然后就到此为止了——“我们都是同意的成年人”,没有一个理智的人会改变一个常量。当然,除非他有很好的理由并且确切地知道他在做什么,在这种情况下你不能(而且可能不应该)以任何方式阻止他。

但是当然,您可以定义带有值的模块级名称并在另一个模块中使用它。这不是特定于常量或任何东西,请在模块系统上阅读。

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT

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.

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT
别把无礼当个性 2024-11-22 11:53:37

当然你可以这样做:

# a.py
MY_CONSTANT = ...

# b.py
from a import *
print MY_CONSTANT

And ofcourse you can do:

# a.py
MY_CONSTANT = ...

# b.py
from a import *
print MY_CONSTANT
度的依靠╰つ 2024-11-22 11:53:37

当然,您可以将常量放入单独的模块中。例如:

const.py:

A = 12
B = 'abc'
C = 1.2

main.py:

import const

print const.A, const.B, const.C

注意上面声明的,ABC都是变量,即可以改变在运行时。

Sure, you can put your constants into a separate module. For example:

const.py:

A = 12
B = 'abc'
C = 1.2

main.py:

import const

print const.A, const.B, const.C

Note that as declared above, A, B and C are variables, i.e. can be changed at run time.

人间不值得 2024-11-22 11:53:37

尝试查看使用“设置”模块创建常量?我可以阻止修改 Python 中的对象吗?

另一个有用的链接:http://code.activestate.com/recipes/65207-constants-in-python/ 告诉我们以下选项:

from copy import deepcopy

class const(object):

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
            return deepcopy(self.__dict__[name])
        self.__dict__[name] = value

    def __getattr__(self, name, value):
        if self.__dict__.has_key(name):
            return deepcopy(self.__dict__[name])

    def __delattr__(self, item):
        if self.__dict__.has_key(item):
            print 'NOOOOO' # throw exception if needed

CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'

因此您可以创建一个这样的类,然后从 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:

from copy import deepcopy

class const(object):

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
            return deepcopy(self.__dict__[name])
        self.__dict__[name] = value

    def __getattr__(self, name, value):
        if self.__dict__.has_key(name):
            return deepcopy(self.__dict__[name])

    def __delattr__(self, item):
        if self.__dict__.has_key(item):
            print 'NOOOOO' # throw exception if needed

CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'

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.

内心荒芜 2024-11-22 11:53:37

作为使用几个答案中描述的导入方法的替代方法,请查看 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.

杀手六號 2024-11-22 11:53:37

使用任意名称创建常量文件,如 my_constants.py
像这样声明常量

CONSTANT_NAME = "SOME VALUE"

对于像这样访问代码导入文件中的常量

import my_constants as constant

并访问常量值 -

constant.CONSTANT_NAME

create constant file with any name like my_constants.py
declare constant like that

CONSTANT_NAME = "SOME VALUE"

For accessing constant in your code import file like that

import my_constants as constant

and access the constant value as -

constant.CONSTANT_NAME
聊慰 2024-11-22 11:53:37

如果您确实想要常量,而不仅仅是看起来像常量的变量,那么标准方法是使用不可变字典。不幸的是它还没有内置,所以你必须使用第三方食谱(比如这个那个)。

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).

吻风 2024-11-22 11:53:37

在商业软件中,常量经常会深埋在许多文件夹中。将以下解决方案与上述解决方案结合使用,以获得最佳效果。这是对我有用的语法:

folder_a
    folder_b
        constants.py
# -----------
# constants.py
# ------------
MAXVAL = 1000

folder_c
    folder_d
        my_file.py

# ------------------------
# my_file.py
# ------------------------
import folder_a.folder_b.constants as consts

print(consts.MAXVAL)

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:

folder_a
    folder_b
        constants.py
# -----------
# constants.py
# ------------
MAXVAL = 1000

folder_c
    folder_d
        my_file.py

# ------------------------
# my_file.py
# ------------------------
import folder_a.folder_b.constants as consts

print(consts.MAXVAL)
谁对谁错谁最难过 2024-11-22 11:53:37

在最近的版本中,它似乎有点挑剔。

顶部答案中的模式

Main.py

import constants
print(token)

constants.py
在此处输入代码token = "12345"

失败。
相反,我必须从常量中导入单个变量。

主.py

from constants import token
print(token)

In more recent editions, it seems a bit pickier.

the mode in the top answer

Main.py

import constants
print(token)

constants.py
enter code heretoken = "12345"

failed.
Instead, I had to import individual variable from constants.

Main.py

from constants import token
print(token)
东京女 2024-11-22 11:53:37

constants.py 文件很好,但我遇到了一种情况,我宁愿将常量放在文件顶部。

类似的 Python 字典需要使用字符串键 dict['A'] 访问变量,但我需要具有与模块导入相同语法的内容。

(出于好奇,我正在处理 Google Collab .ipynb 多个文件,每个文件都有不同的配置变量,并且您无法快速编辑导入的 constants.py 来自 Collab,也不能直接导入另一个 .ipynb 文件)

from dataclasses import dataclass

@dataclass
class Constants:
    A = "foo"

cst = Constants()
print(cst.A)
>>> "foo"

您也可以创建一个经典的 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 imported constants.py from Collab, nor import directly another .ipynb file. )

from dataclasses import dataclass

@dataclass
class Constants:
    A = "foo"

cst = Constants()
print(cst.A)
>>> "foo"

You could also create a classic Python Class, but this needs to define a __init__

烟凡古楼 2024-11-22 11:53:37

这是我的解决方案:

Asum 目录结构

project
|-- package1
|   |-- param1.py
|
|-- package2
|   |-- somefile.py
|
|-- main.py
|-- param2.py

param1.py

MY_CONST = 'abc'

param2.py

MY_CONST = 'xyz'

somefile.py

from package1 import param1

my_var = "inside some file " + param1.MY_CONST

main.py

from package1 import param1
import param2
from package2 import somefile

print(param1.MY_CONST)
print(param2.MY_CONST)
print(somefile.my_var)

运行 main.py

结果:

abc
xyz
inside some file abc

如您所见,您可以使用另一个包中的 const 。
希望这对其他人有帮助!

This is my solution:

Asum Directory structure

project
|-- package1
|   |-- param1.py
|
|-- package2
|   |-- somefile.py
|
|-- main.py
|-- param2.py

param1.py

MY_CONST = 'abc'

param2.py

MY_CONST = 'xyz'

somefile.py

from package1 import param1

my_var = "inside some file " + param1.MY_CONST

main.py

from package1 import param1
import param2
from package2 import somefile

print(param1.MY_CONST)
print(param2.MY_CONST)
print(somefile.my_var)

Run main.py

Result:

abc
xyz
inside some file abc

As you can see, you can use const from another package.
Hope this helps others!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文