Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Overriding method in subclass with a parameter type hint that is a subclass of the type hint used in the parent's method

$
0
0

I have the following structure of a parent class and a child class which inherits from parent. The constructor of the parent takes a parameter of type ParentType, and the constructor of the child class takes the same parameter, but of type ChildType, which is a subclass of ParentType.

The code runs fine, however mypy complains as it is inferring the type of the parameter from the parent class and not the subclass.

class ParentType:    def __init__(self, param_1: int):        self.param_1 = param_1class ChildType(ParentType):    def __init__(self, param_1: int, param_2: int):        super().__init__(param_1=param_1)        self.param_2 = param_2class Parent:    def __init__(self, a: ParentType):        self.a = aclass Child(Parent):    def __init__(self, a: ChildType):        super().__init__(a=a)child_type = ChildType(param_1=1, param_2=2)child = Child(a=child_type)print(child.a.param_1)  # worksprint(child.a.param_2)  # works, but mypy complains that "ParentType" has no attribute "param_2"; maybe "param_1"?

What would be the correct way to achieve this?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>