Depending on the situation you can check with isinstance
what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).
One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr
might then lead to strange errors.
One nice example is the distinction between iterators and iterables (see this question). The __iter__
methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr
is useless, but isinstance
together with ABC's provides a clean solution.
However, I agree that in most situations the hasattr
approach (described in other answers) is the most appropriate solution.