在 python 属性 class 中,如何用我自己的属性覆盖生成的 __init__

in a python attrs class, how can I override generated __init__ with my own

所以我喜欢使用 attr 但有时我需要做我自己的事情。 我可以用自己的方法覆盖 __init__ 方法吗?

import attr
@attr.s(auto_attribs=True)
class MyClass:
     i: int
     def __init__(self, i, special=None):
          if special:
               self.i = special
          else:
               self.i = i
>>> a = MyClass(i=1,special=2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a = MyClass(i=1,special=2)
TypeError: __init__() got an unexpected keyword argument 'special'

另一个例子:

@attr.s(auto_attribs=True)
class MyOtherClass:
     i: int
     def __init__(self, i, **kwargs):
         self.i = kwargs.get('magic',i)



>>> a = MyOtherClass(i=5,magic=12)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a = MyOtherClass(i=5,magic=12)
TypeError: __init__() got an unexpected keyword argument 'magic'

attrs by Examples”页面显示:

Sometimes, you want to have your class’s __init__ method do more than just the initialization, validation, etc. that gets done for you automatically when using @attr.s. To do this, just define a __attrs_post_init__ method in your class. It will get called at the end of the generated __init__ method.

>>> @attr.s
... class C(object):
...     x = attr.ib()
...     y = attr.ib()
...     z = attr.ib(init=False)
...
...     def __attrs_post_init__(self):
...         self.z = self.x + self.y
>>> obj = C(x=1, y=2)
>>> obj
C(x=1, y=2, z=3)

如果您传递 @attr.s(auto_attribs=True, init=False),属性将不会创建 __init__ 方法(对 repreq、...同样有效)。


从 attrs 20.1.0 开始,如果您传递 @attr.s(auto_attribs=True, auto_detect=True) 或使用 NG API @attr.define(不需要参数),它会自动检测是否存在自定义 __init__(以及所有其他 __ 方法)在当前 class 上并且不会覆盖它。