from typing import TypeVar, Dict, Union
T = TypeVar('T', bound='Superclass')
class Superclass:
@classmethod
def from_dict(cls, dict_: Dict[str, Union[str, None]]) -> T:
return cls(**dict_)
class Subclass(Superclass):
def __init__(self, name: Union[str, None] = None):
self.name = name
def copy(self) -> T:
return self.from_dict({'name': self.name})
Emsure that the from_dict
class method can correctly create instances of the subclasses.
You, @Nils, can use a TypeVar
with a bound type. The TypeVar
allows you to specify that the method can return any subclass of Superclass
, including Subclass
.