program story

긴 상수 목록을 Python 파일로 가져 오기

inputbox 2020. 11. 1. 17:42
반응형

긴 상수 목록을 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()

편집하다.

컴파일러에서

NameError : "글로벌 이름 'MY_CONSTANT_ONE'이 정의되지 않았습니다."

myExample의 function init at line 13 self.someValueOne = Constants.MY_CONSTANT_ONE + 1 copy output 프로그램이 0.06 초 후 코드 # 1로 종료되었습니다.


Python은 전처리되지 않습니다. 파일을 만들 수 있습니다 myconstants.py.

MY_CONSTANT = 50

그리고 그것들을 가져 오면 작동합니다.

import myconstants
print myconstants.MY_CONSTANT * 2

파이썬에는 전처리 기가 없으며 변경할 수 없다는 의미에서 상수도 없습니다. 항상 변경할 수 있습니다 (거의 상수 객체 속성을 에뮬레이션 할 수 있지만 상수 성을 위해이 작업을 수행하는 경우는 거의 없습니다). 완료되고 유용하지 않은 것으로 간주 됨) 모든 것. 상수를 정의 할 때, 우리는 이름을 밑줄이있는 대문자로 정의하고 "우리는 모두 여기서 성인에 동의합니다"라고 부릅니다. 정상적인 사람은 상수를 변경할 수 없습니다. 물론 그가 아주 타당한 이유가 있고 그가 무엇을하고 있는지 정확히 알고 있지 않는 한, 당신은 그를 막을 수 없다 (그리고 합당하게도 안된다).

그러나 물론 값으로 모듈 수준 이름을 정의하고 다른 모듈에서 사용할 수 있습니다. 이것은 상수 나 그 어떤 것에 만 국한되지 않으며 모듈 시스템에서 읽습니다.

# a.py
MY_CONSTANT = ...

# b.py
import a
print a.MY_CONSTANT

And ofcourse you can do:

# a.py
MY_CONSTANT = ...

# b.py
from a import *
print MY_CONSTANT

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.


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.


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.


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

참고URL : https://stackoverflow.com/questions/6343330/importing-a-long-list-of-constants-to-a-python-file

반응형