
python中当一个类的属性过多的时候,写的比较麻烦。
1 2 3 4 5 6 7
|
class (object): def __init__(self, a, b, c, d, e=1): self.a = a self.b = b self.c = c self.d = d self.e = e
|
如果想打印类对象的时候友好一些,还需要定义__repr__
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
In [3]: t1 = Test(1,2,3,4,5)
In [4]: t1 Out[4]: <__main__.Test at 0x10ca38908>
In [5]: class Test1(Test): ...: def __repr__(self): ...: return '{}(a={}, b={}, c={})'.format(self.__class__.__name__, se ...: lf.a, self.b, self.c) ...:
In [6]: t1=Test1(1,2,3,4)
In [7]: t1 Out[7]: Test1(a=1, b=2, c=3)
|
如果要比较大小,还需要把 __eq__, __gt__, __lt__,都写出来。
attrs就为解决上述痛点而生。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
In [8]: import attr
In [9]: @attr.s ...: class Test2(object): ...: a = attr.ib() ...: b = attr.ib() ...: c = attr.ib() ...: d = attr.ib() ...: e = attr.ib(default=1) ...:
In [10]: test2=Test2(1,2,3,4)
In [11]: test2 Out[11]: Test2(a=1, b=2, c=3, d=4, e=1)
In [12]: test3=Test2(2,3,4,5)
In [13]: test2>test3 Out[13]: False
In [14]: test2<test3 Out[14]: True
In [15]: attr.asdict(test2) Out[15]: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}
|
除此之外,attrs还支持类型转化,字段验证等
近期评论