how to annotate an argument that is supposed to be a class or its sub-classes ? Not using Union since this is not elegant.
Let's have a minimal example :
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
class Segment(Point):
def __init(self,point1,point2):
self.p1 = point1
self.p2 = point2
def random_function(point_or_segment : Point_and_subclasses):
pass
CodePudding user response:
In this case the type would look like
from typing import Type
def random_function(point_or_segment: Type[Point]):
which denotes point_or_segment should be an instance of Point or an instance of a subclass of Point.
From the docs
Sometimes you want to talk about class objects that inherit from a given class. This can be spelled as
type[C](or, on Python 3.8 and lower,typing.Type[C]) whereCis a class. In other words, whenCis the name of a class, usingCto annotate an argument declares that the argument is an instance ofC(or of a subclass ofC), but usingtype[C]as an argument annotation declares that the argument is a class object deriving fromC(orCitself).
CodePudding user response:
from typing import Type
def random_function(point_or_segment: Type[Point]):
pass
