[英]How to solve "unexpected keyword argument" with python-attrs construct, so that mypy is happy?
I have a class A
in a foreign library.我在外国图书馆有一个
class A
。
class A:
def __init__(self, a: int):
self.a = a
I would like to extend a class B
with A
like:我想用
A
扩展class B
,例如:
import attr
@attr.s
class B(A):
b: int = attr.ib()
The code seems to work:代码似乎有效:
import attr
class A:
def __init__(self, a: int):
self.a = a
attr.s(these={
"a": attr.ib(type=str)
}, init=True)(A)
@attr.s(kw_only=True)
class B(A):
b: int = attr.ib()
if __name__ == "__main__":
a = A(1)
b = B(a=1, b=2)
print(a) # output: A(a=1)
print(b) # output: B(a=1, b=2)
but mypy/pyright is unhappy.但是 mypy/pyright 不高兴。
> mypy file.py
error: Unexpected keyword argument "a" for "B"
I'm reasonably sure that the MyPy attrs plugin doesn't support these
.我有理由确定 MyPy attrs 插件不支持
these
.
Since you're not calling super
, the idiomatic way would be to just define a
as an attribute on B
so that attrs takes care of it.由于您没有调用
super
,惯用的方法是将a
定义为B
上的属性,以便 attrs 处理它。
JFTR: if you use @attr.define
or @attr.s(auto_attribs=True)
, you can leave out the attr.ib()
call(s). JFTR:如果您使用
@attr.define
或@attr.s(auto_attribs=True)
,则可以attr.ib()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.