[FIXED] Type mismatch when using subclasses

Issue

The following code gives me a type mismatch error under strict typeschecking in Python.

class DataClass1(ABC):
    @abstractmethod
    def to_int(self) -> int:
        return 1

class DataClass2(DataClass1):
    def __init__(self, value: int):
        self.value = value
    
    def to_int(self) -> int:
        return self.value 

class WidgetClass(ABC):
    @abstractmethod
    def calculate(self, data: DataClass1) -> DataClass1:
        pass

class WidgetClassImp(WidgetClass):
    def calculate(self, data: DataClass2):
        return data

The WidgetClassImp which receives a subclass of DataClass1 as argument causes the typemismatch to occur. This is surprising as DataClass2 is a subclass of DataClass1 and implements the DataClass1 interface.

Am I doing something wrong?


Solution

A subclass is not the parent class. Therefore declaring WidgetClassImp needing a Dataclass2 changes the funcion signature to its parent therefore typemismatch. You need to also declare Dataclass1 as Parameter and inside the logic either cast to Dataclass2 or only use dataclass1 members.



Answered By - 4lexKidd
Answer Checked By - David Goodson (Python.Easybugfix Volunteer)

Related Posts

Post a Comment