Skip to content
Advertisement

Inheritable custom class constructor in python

How can I implement a custom constructor (class method) that is inheritable in python?

The following minimized example might give an idea:

JavaScript

mypy does not like the constructor I call when returning from from_float. I don’t know how to refer to class (Parent or Child) from the class method.

Advertisement

Answer

Pass the bound argument to TypeVar to specify that the type is a subclass of Parent. This lets mypy know that the type has the something attribute

When you create the instance use cls not Type[T]

JavaScript
Advertisement