Use the built-in function isinstance.
if isinstance(obj, MyClass): print "obj is my object"You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, …)), and can also check whether an object is one of Python’s built-in types. Examples:
if isinstance(obj, str): print repr(obj), "is an 8-bit string" if isinstance(obj, basestring): print repr(obj), "is some kind of string" if isinstance(obj, (int, long, float, complex)): print obj, "is a built-in number type" if isinstance(obj, (tuple, list, dict, set)): print "object is a built-in container type"Note that most programs do not use isinstance on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object’s class and doing a different thing based on what class it is. For example, if you have a function that does something:
def search(obj): if isinstance(obj, Mailbox): print "search a mailbox" elif isinstance(obj, Document): print "search a document" else: print "unknown object"A better approach is to define a search() method on all the classes and just call it:
class Mailbox: def search(self): print "search a mailbox" class Document: def search(self): print "search a document" obj.search()
No comments:
Post a Comment