79309269

Date: 2024-12-26 10:50:58
Score: 1
Natty:
Report link
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.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @Nils
  • Low reputation (1):
Posted by: Nikolai Vorobiev