Declaring a supertype as variable type
Sometimes the inferred type is a subtype (subclass) of the desiredtype. The type inference uses the first assignment to infer the typeof a name (assume here that Shape
is the base class of bothCircle
and Triangle
):
- shape = Circle() # Infer shape to be Circle
- ...
- shape = Triangle() # Type error: Triangle is not a Circle
You can just give an explicit type for the variable in cases such theabove example:
- shape = Circle() # type: Shape # The variable s can be any Shape,
- # not just Circle
- ...
- shape = Triangle() # OK