python 定义字典列表_Python-定义常量列表或字典的最佳/最简洁方法

1586010002-jmsa.png

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

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

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.

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.

THANK YOU SO MUCH!

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值