Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

4.14 Testing Objects and Classes

If you have a reference to something and you want to know if it is an instance of some class, you can use the isinstance(obj,c) built-in function. This will return true if the object obj is an instance of the class c, or any subclass of c, so if isinstance(x,AbstractSet):stuff will execute the stuff if x is an instance of a ListSet or a DictSet.

The function isinstance() works for types as well as for classes. If c is a type object, it will return true if obj is an object of that type. One way to get a type object is to use the type(x) built-in function, which will give you the type object for x's type: For example, if isinstance(x,type(1)):stuff will execute the stuff if x is an integer. Similarly, you can find type objects in the types module. If you have imported types, then if isinstance(x,types.IntType ):stuff will do the same thing.

Unlike many other object-oriented languages, classes in Python are not types. The type(x) call for instance x of class C will not give you C. (Jpython, an implementation of Python in Java, may be an exception to this.) All class instances are objects of type types.InstanceType. The way you can find x's class is by using its special attribute __class__. So if x.__class__ is AbstractSet :stuff will execute the stuff if x is an instance of a AbstractSet, but neither ListSet nor DictSet. A "special attribute" is an attribute that's built in to an instance object and is always present.

Classes themselves are objects of type types.ClassType. The types are of type types.TypeType. Figure 4–15 diagrams the relationships among instances, classes, and types.

Figure 4-15Figure 4–15 Relationships among instances, classes, and types.

You can test classes' relationships in an inheritance hierarchy with the issubclass(c1,c2) built-in function, which returns true if class c1 is the same as c2 or if c1 inherits from c2.

  • + Share This
  • 🔖 Save To Your Account