Python-定义常量列表或字典的最佳/最简洁方法 [英] Python - Best/Cleanest way to define constant lists or dictionarys

查看:829
本文介绍了Python-定义常量列表或字典的最佳/最简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次遇到堆栈溢出的用户,我很高兴来到这里.

First time user on stack overflow and I'm excited to be here.

INTRO:我最近开始了进入Python编程世界的神奇冒险-我喜欢它.现在,在从C进行尴尬的转换时,一切都进行得很顺利,但是我在创建与HEADER文件(.h)相同的东西时遇到了麻烦.

INTRO: I recently began the magical adventure into the world of Python programming - I love it. Now everything has gone smoothly in my awkward transition from C, but I'm having trouble creating something which would be synonymous to a HEADER file (.h).

问题:我有中等大小的字典和列表(大约1000个元素),冗长的枚举和"#defines"(不是很准确),但是我找不到一种清晰的方式来组织它们.在C语言中,我会将它们全部放在头文件中,再也无需考虑它了,但是,在Python中这是不可能的,所以我想.

PROBLEM: I have medium sized dictionaries and lists (about 1,000 elements), lengthy enums, and '#defines' (well not really), but I can't find a CLEAN way to organize them all. In C, I would throw them all in a header file and never think again about it, however, in Python that's not possible or so I think.

当前脏污解决方案:我正在对MODULE或FUNCTION(如果需要多个功能,则为模块)顶部的所有CONSTANT变量进行初始化.

CURRENT DIRTY SOLUTION: I'm initializing all CONSTANT variables at the top of either the MODULE or FUNCTION (module if multiple functions need it).

结论:如果有人想出一种方法来清晰地组织常数变量,我将永远感激不尽.

CONCLUSION: I would be forever grateful if someone had come up with a way to CLEANLY organize constant variable's.

非常感谢您!

推荐答案

将常量放入自己的模块中

Put your constants into their own module:

# constants.py

RED = 1
BLUE = 2
GREEN = 3

然后导入该模块并使用常量:

Then import that module and use the constants:

import constants

print "RED is", constants.RED

常量可以是任何您喜欢的值,我在这里显示了整数,但是列表和字典将完全一样.

The constants can be any value you like, I've shown integers here, but lists and dicts would work just the same.

这篇关于Python-定义常量列表或字典的最佳/最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆