Python-Ref > Object oriented programming > Introspection > Asking members by their name
 
 

<-^^->

Asking members by their name

How to query an attribute or a method using its name as a string.
Python has three different functions for the task at hand - hasattr, getattr and setattr. Usage of all of them is demonstrated in the following snippet.
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   
 42   print hasattr( o1, "color")
 43   if hasattr( o3, "color"):
 44     print getattr( o3, "color")
 45     print o3.color
 46   
 47   if hasattr( o4, "text"):
 48     print o4.text
 49     setattr( o4, "text", "New text")
 50     print o4.text
 51   
 52   print getattr( o2, "get_area")
 53   print getattr( o2, "get_area")()
 54   
 55   for o in [o1,o2,o3,o4]:
 56     if hasattr( o, "get_area"):
 57       print "%s has area %d" % (o, getattr( o, "get_area")())
 58     else:
 59       print "%s does not support area" % o
stdout:
True
white
white
Hello world!
New text
<bound method Rectangle.get_area of <__main__.Rectangle instance at 0x2b1a7b876560>>
15
<__main__.Rectangle instance at 0x2b1a7b85af38> has area 6
<__main__.Rectangle instance at 0x2b1a7b876560> has area 15
<__main__.Circle instance at 0x2b1a7b8765a8> has area 50
<__main__.Text instance at 0x2b1a7b8765f0> does not support area
Doba běhu: 35.3 ms
The result of getattr function is often combined with using the 'callable' function.
For access to object attributes (not methods or properties), there is different way available. This approach uses the special __dict__ attribute of an object that contains a dictionary mapping between object attributes and their values.
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   
 42   print o1.__dict__
 43   print o1.__dict__['color']
 44   
 45   for o in [o1,o2,o3]:
 46     if 'text' in o.__dict__:
 47       print "%s has text '%s'" % (o, o.__dict__['text'])
 48     else:
 49       print "%s has no text" % o
 50   
 51   print "Rectangle color: %(color)s, width: %(width)d, height: %(height)d" % o2.__dict__
stdout:
{'color': 'black', 'width': 2, 'height': 3}
black
<__main__.Rectangle instance at 0x2b265234eef0> has no text
<__main__.Rectangle instance at 0x2b265234efc8> has no text
<__main__.Circle instance at 0x2b2652366440> has no text
Rectangle color: yellow, width: 3, height: 5
Doba běhu: 21.6 ms
Yet another way to list all available members of an object is to use the built-in function dir. It returns a list on names of all the members of an object, that is both attributes and methods.
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   
 42   print dir( o1)
 43   print "--------------------"
 44   for x in dir( o1):
 45     member = getattr( o1, x)
 46     if x.startswith( "__") and x.endswith("__"):
 47       if callable( member):
 48         print "Special method", x
 49       else:
 50         print "Special attribute", x
 51     else:
 52       if callable( member):
 53         print "Method", x
 54       else:
 55         print "Attribute", x
 56   print "--------------------"    
 57   if "get_area" in dir( o3) and callable( o3.get_area):
 58     print "Area of o3 is", o3.get_area()
stdout:
['__doc__', '__init__', '__module__', 'color', 'get_area', 'height', 'width']
--------------------
Special attribute __doc__
Special method __init__
Special attribute __module__
Attribute color
Method get_area
Attribute height
Attribute width
--------------------
Area of o3 is 50.264
Doba běhu: 21.8 ms