python 中的可继承自定义 class 构造函数

Inheritable custom class constructor in python

如何实现可在 python 中继承的自定义构造函数(class 方法)?

下面的最小化示例可能会提供一个思路:

from dataclasses import dataclass
from typing import Type, TypeVar

T = TypeVar("T")


@dataclass
class Parent:
    something: int = 2

    @classmethod
    def from_float(cls: Type[T], something_as_float: float) -> T:
        return Type[T](something=int(something_as_float))


@dataclass
class Child(Parent):
    """ Should also be constructible via from_float
    """


assert isinstance(Parent.from_float(1.0), Parent)
assert isinstance(Child.from_float(1.0), Child)

mypy 不喜欢我从 from_float 返回时调用的构造函数。我不知道如何从 class 方法中引用 class(父或子)。

bound 参数传递给 TypeVar 以指定该类型是 Parent 的子类。这让 mypy 知道该类型具有 something 属性

创建实例时使用 cls 而不是 Type[T]

from dataclasses import dataclass
from typing import Type, TypeVar

T = TypeVar("T", bound='Parent')


@dataclass
class Parent:
    something: int = 2

    @classmethod
    def from_float(cls: Type[T], something_as_float: float) -> T:
        return cls(something=int(something_as_float))


@dataclass
class Child(Parent):
    pass


assert isinstance(Parent.from_float(1.0), Parent)
assert isinstance(Child.from_float(1.0), Child)