Python-Ref > Object oriented programming > Introspection > Checking parentage
 
 

<-^^->
Moduly
Knihovní funkce

Checking parentage

Is an object instance of a specific class? Or class subclass of another class?
One of the most basic functions of introspection is to find out if an object is derived from a specific class. We may use this kind of introspection to ensure that our code accepts only objects of certain parentage, thus having certain inherited properties.
Expand/Shrink
  1   class Shape:
  2   
  3     def __init__( self, color):
  4       self.color = color
  5   
  6     def get_area( self):
  7       return 0
  8   
  9   
 10   class Rectangle( Shape):
 11   
 12     def __init__( self, color, width, height):
 13       Shape.__init__( self, color)
 14       self.width = width
 15       self.height = height
 16   
 17     def get_area( self):
 18       return self.width * self.height
 19   
 20   
 21   class Circle( Shape):
 22   
 23     def __init__( self, color, radius):
 24       Shape.__init__( self, color)
 25       self.radius = radius
 26   
 27     def get_area( self):
 28       return 3.1415 * self.radius**2
 29   
 30   
 31   class Text:
 32   
 33     def __init__( self, color, text):
 34       self.color = color
 35       self.text = text
 36     
 37   o1 = Rectangle( "black", 2, 3)
 38   o2 = Rectangle( "yellow", 3, 5)
 39   o3 = Circle( "white", 4)
 40   o4 = Text( "green", "Hello world!")
 41   objects = [o1, o2, o3, o4]
 42   
 43   # for instances we use isinstance..
 44   for o in objects:
 45     if isinstance( o, Shape):
 46       print "Shape:", o.__class__.__name__, "- color:", o.color, "- area:", o.get_area()
 47     else:
 48       print "Not shape:", o
 49   
 50   print "----------"
 51   # .. for classes issubclass
 52   print issubclass( Rectangle, Shape)
 53   print issubclass( o1.__class__, Shape)  # same as isinstance( o1, Shape)
 54   print issubclass( Shape, Shape)
 55   print issubclass( Text, Shape)
 56   print "----------"
 57   # difference between isinstance and x.__class__ == class
 58   print isinstance( o1, Rectangle), o1.__class__ == Rectangle
 59   print isinstance( o1, Shape), o1.__class__ == Shape
stdout:
Shape: Rectangle - color: black - area: 6
Shape: Rectangle - color: yellow - area: 15
Shape: Circle - color: white - area: 50.264
Not shape: <__main__.Text instance at 0x2adb0ed68638>
----------
True
True
True
False
----------
True True
True False
Doba běhu: 31.3 ms
You may find more examples of use of isinstance function in Getting text from an element.