Unit 13Classes in Python
Follows IGNOU MCS-201, Unit 13
So far your programs have been organised around functions acting on data. Object-oriented programming (OOP) organises them around objects that bundle data with the operations on that data. This unit shows how to define classes and create objects in Python, how constructors and instance and class variables work, how classes reuse code through inheritance and composition, what class and static methods are for, how to give your own classes operators such as + and >, and how polymorphism lets different objects respond to the same request in their own way.
In this unit you will learn to
- Explain the object-oriented idea and define classes, objects, attributes and methods.
- Write constructors with
__init__, and useself, instance variables and class variables correctly. - Build single, multilevel, multiple and hierarchical inheritance, call parent methods with
super(), and read the method resolution order. - Combine objects with composition (“has-a”) and decide between composition and inheritance.
- Write instance, class and static methods.
- Overload operators such as
+,>and==and control printing with__str__. - Explain polymorphism through duck typing, operator overloading and method overriding.
Sections in this unit
- 13.1Object-Oriented Programming: Classes and ObjectsThe object-oriented idea, what classes and objects are, how to define a class with attributes and methods, and how each object gets its own namespace.10 min
- 13.2Constructors, Instance Variables and Class VariablesHow __init__ initialises new objects, the meaning of self, the difference between instance and class variables, and printing objects with __str__.10 min
- 13.3InheritanceReusing code by deriving classes: single, multilevel, multiple and hierarchical inheritance, constructors and super(), and the method resolution order.11 min
- 13.4CompositionBuilding classes out of other objects ("has-a"), how composition differs from inheritance ("is-a"), and when to prefer each.8 min
- 13.5Instance, Class and Static MethodsThe three kinds of methods in a Python class, the @classmethod and @staticmethod decorators, what each receives, and when to use each.8 min
- 13.6Operator OverloadingHow Python operators call special methods, and how to define those methods so your own classes work with operators such as plus and greater-than.8 min
- 13.7PolymorphismOne interface, many forms: duck typing, operator overloading, method overriding, and why Python does not support method overloading.11 min