如何實作可在python中繼承的自定義建構式(類方法)?
以下最小化示例可能會給出一個想法:
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 回傳時呼叫的建構式。我不知道如何從類方法中參考類(父或子)。
uj5u.com熱心網友回復:
將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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314632.html
