Introspection

John Lehmann jlehmann at nsw.bigpond.net.au
Mon Feb 28 08:25:01 EST 2000


These two functions might help you to play with classes:

  isinstance (object, class) 
  issubclass (class1, class2) 

There is also a __class__ attribute

>>> class A:
>>> 	pass
>>> a = A()
>>> isinstance(a, A)
1
>>> hasattr(a, '__class__')
1
>>> hasattr(6, '__class__')
0

Chuck Esterbrook wrote:
> 
> If I want a handle/pointer to an instance's class, how do I do that?
> 
> In Objective-C I can say:
>     [someObject class]
> 
> Which in Python would be:
>     someObject.class()
> 
> However, Python doesn't have a well-defined root class with such utility methods. Also, I also don't see anything useful from:
>     dir(someObject)
> 
> Also, I notice the following oddity: I can use the __name__ attribute to get the name of a class, but if I say "dir(someClass)", I get attributes like __doc__ and __module__, but no __name__.  How does Python get the __name__ then?
> 
> >>> class Foo:
> ...     pass
> ...
> >>> Foo.__name__
> 'Foo'
> >>> dir(Foo)
> ['__doc__', '__module__']
> >>>
> 
> -Chuck



More information about the Python-list mailing list