What's the best way to initialise and use constants across Python classes?

后端 未结 4 1494
天涯浪人
天涯浪人 2020-12-30 18:46

Here\'s how I am declaring constants and using them across different Python classes:

# project/constants.py
GOOD = 1
BAD = 2
AWFUL = 3

# project/question.py         


        
4条回答
  •  Happy的楠姐
    2020-12-30 19:41

    You have a few options:

    1. Do it the way you're doing right now with a file of constants
    2. Use a flat file and parse it once, pass a dictionary / class around
    3. Query off to a database

    From an overhead point of view, 1 and 2 are about the same. As for your question about importing specific constants, it's much easier to use one of the following conventions:

    • import constants; some_func(constants.AWFUL)
    • from constants import *; some_func(AWFUL)

提交回复
热议问题