Home > Net >  how to annotate class and subclasses ? python
how to annotate class and subclasses ? python

Time:01-13

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]) where C is a class. In other words, when C is the name of a class, using C to annotate an argument declares that the argument is an instance of C (or of a subclass of C), but using type[C] as an argument annotation declares that the argument is a class object deriving from C (or C itself).

CodePudding user response:

from typing import Type

def random_function(point_or_segment: Type[Point]):
   pass
  • Related