python类实用程序
class-tools的Python项目详细描述
python类实用程序
class-tools
是python类的实用程序集合,作者
经常需要。
我能用class-tools
做什么?
快速向类添加属性
fromclass_tools.decoratorsimportwrapper_property@wrapper_property("name",default=lambda:"Bob",doc="The dog's name")@wrapper_property("toy",default=lambda:"ball")@wrapper_property("sharp_teeth",default=lambda:4,type=int)classDog:passdog=Dog()dog.__doc__# "The dog's name"dog.name# 'Bob'dog.toy# 'ball'dog.sharp_teeth="4"# (set as a string value)dog.sharp_teeth# 4 (returned as int)
添加一个漂亮的__repr__
方法
fromclass_tools.decoratorsimport*@with_init_from_properties()@with_repr_like_init_from_properties()@wrapper_property("name")@wrapper_property("furcolor")classCat:passcat=Cat(name="Lucy",furcolor="white")cat# Cat(# furcolor = 'white',# name = 'Lucy'# )
使类可按属性进行比较
fromclass_tools.decoratorsimport*@with_eq_comparing_properties()@wrapper_property("name")@wrapper_property("furcolor")classCat:passlucy=Cat()lucy.name="Lucy"lucy.furcolor="white"lucy_clone=Cat()lucy_clone.name="Lucy"lucy_clone.furcolor="white"gary=Cat()gary.name="Gary"lucy==gary# Falselucy==lucy_clone# True
以上均
fromclass_tools.propertyobjectimportPropertyObjectfromclass_tools.decoratorsimportwrapper_property@wrapper_property("name")@wrapper_property("height",type=float)@wrapper_property("friends",type=list,default=list)classGiraffe(PropertyObject):passmatt=Giraffe(name="Matt")matt.height=3gunther=Giraffe(name="Gunther")gunther.friends.append(matt)gunther# Giraffe(# friends=[Giraffe(# friends=[],# height=3.0,# name='Matt'# )],# height=None,# name='Gunther'# )
安装
最好通过pip
安装class-tools
包。从任何地方运行:
python3 -m pip install --user class-tools
这将从Python Package Index下载并安装包。
您还可以从存储库根目录安装class-tools
:
python3 -m pip install --user .
文档
可以找到class-tools
包的文档here on
GitLab。
另外,命令行帮助页python3 -m class-tools -h
是您的朋友。