Python-Ref > Object oriented programming > Introspection > Distinguishing between attributes and methods
 
 

<-^^->

Distinguishing between attributes and methods

When using the hasattr function, we can only find out if an object has a member with a specific name, but we cannot see if it is an attribute or a method. For this purpose we can use the built-in function called callable which tells us wether an object may be used as a function.
Expand/Shrink
  1   class Rectangle:
  2   
  3     def __init__( self, width, height):
  4       self.width = width
  5       self.height = height
  6   
  7     def area( self):
  8       return self.width * self.height
  9   
 10   
 11   class Circle:
 12   
 13     def __init__( self, area):
 14       self.area = area
 15   
 16     def radius( self):
 17       import math
 18       return math.sqrt( self.area / 3.1415)
 19   
 20   
 21   o1 = Rectangle( 2, 3)
 22   o2 = Rectangle( 3, 5)
 23   o3 = Circle( 4)
 24   
 25   print hasattr( o1, "area"), callable( getattr( o1, "area"))
 26   print hasattr( o3, "area"), callable( getattr( o3, "area"))
 27   print o1.area
 28   print o3.area
 29   
 30   for o in [o1,o2,o3]:
 31     if hasattr( o, "area"):
 32       x = getattr( o,"area")
 33       if callable( x):
 34         print "%s has area %d" % (o, x())
 35       else:
 36         print "%s has area %d" % (o, x)
 37   
 38   print callable( Rectangle)
stdout:
True True
True False
<bound method Rectangle.area of <__main__.Rectangle instance at 0x2acccec1bf38>>
4
<__main__.Rectangle instance at 0x2acccec1bf38> has area 6
<__main__.Rectangle instance at 0x2acccec30d40> has area 15
<__main__.Circle instance at 0x2acccec30d88> has area 4
True
Doba běhu: 30.1 ms
The following example shows that the callable function might be used for any other type of value, not only for objects and their members.
Expand/Shrink
  1   import math
  2   
  3   def whatever( x):
  4     return x + 4
  5   
  6   print callable( whatever)
  7   print callable( math.sin)
  8   print callable( math.pi)
  9   print callable( 4)
 10   print callable( file)
 11   
 12   x = math.cos
 13   print callable( x)
stdout:
True
True
False
False
True
True
Doba běhu: 26.0 ms