Python-Ref > Object oriented programming > Introspection > Introspection introduction
 
 

^^->
Klíčová slova
Moduly
Knihovní funkce

Introspection introduction

What is introspection and some basic approaches.
One of the most interesting features of Pythons OOP implementation is that it makes introspection very simple. That means that it is very simple to find out which attributes or methods an object implements and what is its parentage.
Introspection makes it possible to write more general code and when used carefully may complement inheritance in creation of object with similar interfaces.
Expand/Shrink
  1   class Rectangle:
  2   
  3     def __init__( self, color, width, height):
  4       self.color = color
  5       self.width = width
  6       self.height = height
  7   
  8     def get_area( self):
  9       return self.width * self.height
 10   
 11   
 12   class Text:
 13   
 14     def __init__( self, color, text):
 15       self.color = color
 16       self.text = text
 17     
 18   
 19   r1 = Rectangle( "black", 10, 2)
 20   t1 = Text( "red", "Hello")
 21   
 22   print r1.__class__
 23   print r1.__class__.__name__
 24   
 25   print t1.__class__.__name__
stdout:
__main__.Rectangle
Rectangle
Text
Doba běhu: 70.8 ms
Expand/Shrink
  1   class Rectangle:
  2     """class representing a rectangle"""
  3   
  4     def __init__( self, color, width, height):
  5       self.color = color
  6       self.width = width
  7       self.height = height
  8   
  9     def get_area( self):
 10       return self.width * self.height
 11   
 12   
 13   class Text:
 14     """colored text"""
 15   
 16     def __init__( self, color, text):
 17       self.color = color
 18       self.text = text
 19     
 20   
 21   r1 = Rectangle( "black", 10, 2)
 22   t1 = Text( "red", "Hello")
 23   
 24   print dir( r1)
 25   print r1.__dict__
 26   r1.__dict__['color'] = "green"
 27   print r1.__dict__
 28   print r1.color
 29   print t1.__class__.__dict__
 30   
 31   print "\n----------\n"
 32   
 33   print dir( t1.__class__)
 34   print t1.__doc__
 35   print t1.__class__.__doc__
 36   t1.__doc__ = "text instance"
 37   print t1.__doc__
 38   print t1.__class__.__doc__
stdout:
['__doc__', '__init__', '__module__', 'color', 'get_area', 'height', 'width']
{'color': 'black', 'width': 10, 'height': 2}
{'color': 'green', 'width': 10, 'height': 2}
green
{'__module__': '__main__', '__doc__': 'colored text', '__init__': <function __init__ at 0x2ba35e3b29b0>}

----------

['__doc__', '__init__', '__module__']
colored text
colored text
text instance
colored text
Doba běhu: 30.8 ms