给Mypy开心的抽象班级构造函数的正确方法是什么?
我有一个抽象基类 BsaeFoo
,我的数据类(例如 ChildFoo
)继承自它。
from abc import ABCMeta
from typing import Dict, Any, TypeVar, Type
from dataclasses import dataclass
Foo = TypeVar("Foo", bound="BaseFoo")
class BaseFoo(metaclass=ABCMeta):
@classmethod
def from_dict(cls: Type[Foo], data: Dict[str, Any]) -> Foo:
init_data = {key: data.get(key, None) for key in cls.__annotations__}
return cls(**init_data)
@dataclass
class ChildFoo(BaseFoo):
x: int
y: int
运行 Mypy 使我的
main.py:12: error: Too many arguments for "BaseFoo"
Found 1 error in 1 file (checked 1 source file)
from_dict
将成为子数据类的替代构造函数。它根据 cls.__annotations__ 属性读取输入字典,因此它不会在子类中引发。至于BaseFoo
本身,检查初始化是没有意义的,因为它是一个抽象类。
如何在不使用 # type:ignore
的情况下使 BaseFoo.from_dict
传递 Mypy ?
I have an abstract base class BsaeFoo
that my dataclasses such as ChildFoo
is inheriting from.
from abc import ABCMeta
from typing import Dict, Any, TypeVar, Type
from dataclasses import dataclass
Foo = TypeVar("Foo", bound="BaseFoo")
class BaseFoo(metaclass=ABCMeta):
@classmethod
def from_dict(cls: Type[Foo], data: Dict[str, Any]) -> Foo:
init_data = {key: data.get(key, None) for key in cls.__annotations__}
return cls(**init_data)
@dataclass
class ChildFoo(BaseFoo):
x: int
y: int
Running Mypy gives me
main.py:12: error: Too many arguments for "BaseFoo"
Found 1 error in 1 file (checked 1 source file)
from_dict
would be an alternative constructor of the child dataclasses. It reads the input dict based on the cls.__annotations__
attribute, so it won't raise in the child classes. As for BaseFoo
itself, it does not make sense to check initialization since it is an abstract class.
How do I make BaseFoo.from_dict
pass Mypy without using # type: ignore
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

在
BaseFoo
中添加__init__
的显式定义Add explicit definition of
__init__
inBaseFoo