提供管理常量变量的广泛方法。
constant2的Python项目详细描述
欢迎使用constant2文档
如果你有很多constant2的价值在你的开发中被广泛使用。更好的方法是定义Constantant Variable,而不是使用原始值。这可以提高可读性和可访问性。
constant2是一个库,提供了管理constant2变量的广泛方法。
另一个强大的功能是,constant2允许开发人员定义规范化的实体关系,并且是class样式的数据,这为每一行和每一列提供了极好的可访问性,使开发人员从记忆中解脱出来。
使用量
版本已更改0.0.9:所有嵌套类现在都必须从Constant或其子类继承:
# WRONG!classItemType(Constant):classWeapon:id=1# CORRECTclassItemType(Constant):classWeapon(Constant):id=1# orclassItem(Constant):passclassItemType(Constant):classWeapon(Item):id=1
用法:
fromconstant2importConstantclassFood(Constant):classFruit(Constant):id=1name="fruit"classApple(Constant):id=1name="apple"classRedApple(Constant):id=1name="red apple"classGreenApple(Constant):id=2name="green apple"classBanana(Constant):id=2name="banana"classYellowBanana(Constant):id=1name="yellow banana"classGreenBanana(Constant):id=2name="green banana"classMeat(Constant):id=2name="meat"classPork(Constant):id=1name="pork"classBeef(Constant):id=2name="beef"food=Food()
您可以通过以下方式访问它的数据或子类数据:
# Use class>>>Fruit.Items()# .Items() return it's data[('id',1),('name','fruit')]>>>Fruit.Keys()# .Keys() return keys['id','name']>>>Fruit.Values()# .Values() return values[1,'fruit']>>>Fruit.ToDict()# return data in a dict{'id':1,'name':'fruit'}# use instance>>>food.items()# .Items() return it's data[('id',1),('name','fruit')]>>>food.keys()# .keys() return keys['id','name']>>>food.values()# .values() return values[1,'fruit']>>>food.to_dict()# return data in a dict{'id':1,'name':'fruit'}# iterate on all nested class>>>Fruit.Subclasses(sort_by='id')[classApple,classBanana]# get first nested class that kls.id == 1# useful when you need reverse lookup>>>Fruit.GetFirst('id',1)classApple# get all child class that kls.id == 1>>>Fruit.GetAll('id',1)[classApple,]
它还提供了内置的i/o方法,允许您将这些数据转储到字典中。
>>>data=Food.dump()>>>data{"Food":{"Fruit":{"Apple":{"GreenApple":{"__classname__":"GreenApple","id":2,"name":"green apple"},"RedApple":{"__classname__":"RedApple","id":1,"name":"red apple"},"__classname__":"Apple","id":1,"name":"apple"},"Banana":{"GreenBanana":{"__classname__":"GreenBanana","id":2,"name":"green banana"},"YellowBanana":{"__classname__":"YellowBanana","id":1,"name":"yellow banana"},"__classname__":"Banana","id":2,"name":"banana"},"__classname__":"Fruit","id":1,"name":"fruit"},"Meat":{"Beef":{"__classname__":"Beef","id":2,"name":"beef"},"Pork":{"__classname__":"Pork","id":1,"name":"pork"},"__classname__":"Meat","id":2,"name":"meat"},"__classname__":"Food"}}>>>Food=Constant.load(data)
安装
constant2在pypi上发布,所以您只需要:
$ pip install constant2
要升级到最新版本:
$ pip install --upgrade constant2