Python 属性在设置属性时触发转换器

Python Attrs Trigger Converter while set attribute

在使用 python-attrs 时,设置属性时触发转换器的好方法是什么。

EX:

@attr.s
class A(object):
   b = attr.ib(converter=str)

>>> A(b=1)
A(b='1')
>>> a = A(b=1)
>>> a.b
'1'
>>> a.b = 2
>>> a.b
2   # converter not used

在你的情况下,你不能使用 attrs 来做到这一点,reference of philosophy:attrs 运行时影响非常接近于零,因为所有工作都是在定义 class 时完成的。一旦你初始化它,attrs 就完全不在画面中了。

查看 attrs real 的作用:

import attr
import inspect


@attr.s
class A(object):
    b = attr.ib(converter=str)


print(inspect.getsource(A.__init__))

输出是

def __init__(self, b):
    self.b = __attr_converter_b(b)

所以你可以看到所有的魔法都只在init函数中完成,所以实例初始化后,attrs不能处理了,如果你真的想控制你自己的设置行为,为什么不使用描述符,这是为 class 属性设计的。