简体   繁体   English

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

[英]Inheritable custom class constructor in python

How can I implement a custom constructor (class method) that is inheritable in python?如何实现可在 python 中继承的自定义构造函数(类方法)?

The following minimized example might give an idea:以下最小化示例可能会提供一个想法:

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 does not like the constructor I call when returning from from_float. mypy 不喜欢我从 from_float 返回时调用的构造函数。 I don't know how to refer to class (Parent or Child) from the class method.我不知道如何从 class 方法中引用 class (Parent or Child)。

Pass the bound argument to TypeVar to specify that the type is a subclass of Parent .bound参数传递给TypeVar以指定该类型是Parent的子类。 This lets mypy know that the type has the something attribute这让 mypy 知道该类型具有something属性

When you create the instance use cls not Type[T]创建实例时使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM