所以我喜欢使用 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'