.. include:: global.rst ============================================= 14: Class and Type ============================================= Summary ============ - There are two main concepts of type - Primitive type: relates to the way data is represented and is the origin of the concept - The second relates to class in object oriented programming - In many object oriented languages defining a class introduces a new type to the type system - A strongly typed language enforces the rule that you have to declare the type of a variable and that variable can from then on only reference objects of that type - This rule is usually extended to include variables referencing objects of the specified type or a subtype - The reason for this si that it allows you to write partly generic methods which can process the type and all its subtypes - Class hierarchy is a model of the real world - The Liskov Substitution Principle is often used as a justification for hierarchial typing, but it is only an approximation to the real world - Variables do not have a type associated with them and can reference any type of object - Objects do have a limited notion of type in that their __class__ attribute is set to the class or metaclass that created them - It is important to realize that __class__ can be modified - You can use isinstance and issubclass to check that an object claims to be of the appropriate type - Another approach is to use defensive programming to test for the presence of any attribute or method you are planning to use via the hasattr function - This is generally called "duck typing" Program ============ .. literalinclude:: programs/chapterFourteen.py :language: python Program Output ================= .. code-block:: console