python - 在 python attrs 类中,如何用我自己的重写生成的 __init__

标签 python python-3.7 python-attrs

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

最佳答案

如果您传递 @attr.s(auto_attribs=True, init=False),attrs 不会创建 __init__ 方法(对于 作用相同>repreq,...)。

<小时/>

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

关于python - 在 python attrs 类中,如何用我自己的重写生成的 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58222483/

相关文章:

python - IndexError : list index out of range in"if. ..否则...”

python - WXPython:填充列表框的问题

python - 如何使用numpy在分段间隔上生成随机数

python - 仅位置参数与 python 3.7 的兼容性

python - 动态定义依赖于先前定义的属性的属性

python-attrs - attrs转换器的装饰器

python - 有没有一种用 `python-attrs` 记录属性的好方法?

python - Linux Python Azure Function APP - 尽管在 requirements.txt 和其他模块中工作正常,但找不到 pyodbc 模块

python - django查询中传入参数

linux - 即使 vm.overcommit_memory=1 ,numpy 也不会过度使用内存