自动初始化实例属性的Python装饰器
autoinit的Python项目详细描述
自动初始化
Python decorator for automatic initialization instance attributes
什么
fromautoinitimportautoinit@autoinitclassX:def__init__(self,a,b,c,d:int,e=99.99,f='some_default_value'):print("__init__ do some another things")x=X(42,100,500,None)# Output: "__init__ do some another things"print(x.__dict__)# Output: {'a': 42, 'b': 100, 'c': 500, 'd': None, 'e': 99.99, 'f': 'some_default_value'}
如何
$pip install autoinit
其中
测试地点:
- CPython:2.7,3.5-3.8
- Pypy:2.7、3.5、3.6
- 杰森:2.7
…但很有可能与其他实现一起工作。在
为什么
在__init__
内的许多基本作业是一个相当频繁且相当枯燥的案例。在
数据类并没有让它更有趣,主要是因为您仍然不能在一行中声明属性
@dataclassclassFiveDimensionRecord:x:inty:intz:intu:intv:intdt:'typing.Any'=Nonedescription:str=''def__post_init__(self):self.dt=self.dtordatetime.now()
使用autoinit
它看起来更加紧凑和简约
classFiveDimensionRecord:@autoinitdef__init__(self,x:int,y:int,z:int,u:int,v:int,dt=None,description:str=''):self.dt=self.dtordatetime.now()
选项
- 在
在@autoinit(exclude='attr')
或@autoinit(exclude=['attr1', 'attr2]')
:跳过指定的属性 - 在
在@autoinit(no_warn=True)
:如果decorator应用于非__init__
方法,则不要抛出警告 - 在
在@autoinit(reverse=True)
:颠倒操作顺序-首先调用包装好的方法(通常是__init__
),然后执行赋值
decorator本身可以同样地应用于__init__
方法和整个类。在
- 项目
标签: