March 1st, 2005, 05:09 PM
Is there a __somename__ that gives class type ?
For exemple if you do classname.__doc__ you will get the docstring of a class.
Is there a similar way to get the class name of a class instance ?
If there is would it be correct to iterate through a list of base class objects and check their real class ( since they all inherit baseclass ) using this value ?
March 1st, 2005, 05:24 PM
You can use the __class__ method to get the type of an instance, however we also have type() and isinstance() functions for doing this type of thing.
I'm not really sure what you meant by iterating over the base classes. In Python every object inherits from the object class.
>>> a = object()
>>> b = dict()
>>> c = str()
>>> isinstance(c, object)
>>> isinstance(c, dict)
March 1st, 2005, 05:34 PM
hey try __module__ to get the class name.
You can always see what all is avaiilable for a class by doing
March 1st, 2005, 05:36 PM
Understanding why it works is left as an exercise... ;-)
class Foo(object): pass
x = Foo()
March 1st, 2005, 05:37 PM
Sorry for being nebulous. I have a list of classes of a common base type but of different inherited types.
I have a loop that iterates through all of the list objects and I wanted to identify which objects were of a certain type.
March 1st, 2005, 07:45 PM
The obvious answer is to use isinstance:
Originally Posted by bleakcabal
The better answer, however, is generally to use Duck Typing:
for obj in mylist:
if isinstance(obj, Foo):
for obj in mylist:
March 3rd, 2005, 01:56 AM
For the record:
1) class instances have an attribute called __class__, that holds (surprise, surprise) the class object. type(obj) will also return the class of an object.
2) class objects have an attribute __bases__, that holds a tuple of the classes they are derived from. However if you just want to test whether a class is derived from a particular base class then it is better to use the isinstance or issubclass functions.
3) new-style classed (derived from object) have an undocumented method __subclasses__ that returns a tuple of the classes DERIVED from the class. This is used internally by Python, and since it is not documented may go away in future versions. It is still occasionally useful for things like debugging and exploring third-party libraries.
Dave - The Developers' Coach