Object-Oriented Programming Basics: Classes, Objects, Attributes, Methods, and Inheritance
Object-oriented programming organises code around classes that bundle state (attributes) with behaviour (methods). The exam tests whether you can define a class, create instances, distinguish class-level from instance-level data, and reason about inheritance and method overriding.
Classes and objects
A class is the blueprint; an object is an instance created from it. The constructor (__init__ in Python) initialises instance attributes. Methods receive the instance as their first parameter (self or this) so they can read and write that instance's data. Calling a method without the instance - or forgetting self in a definition - is a common error.
Attributes and methods
Instance attributes belong to one object and are normally created in the constructor (self.items = []). Class attributes are defined on the class and shared by every instance; they are fine for constants, dangerous for mutable state. Methods can be instance methods, class methods, or static methods, depending on whether they need the instance or the class.
Inheritance
A subclass inherits attributes and methods from its parent and can override methods to change behaviour. super() calls the parent implementation, which is how you extend rather than replace a method. Use inheritance for an is-a relationship; use composition (has-a) when one object simply holds another.
Worked example
class Cart:
items = []
def __init__(self, owner):
self.owner = owner
def add(self, x):
self.items.append(x)
c1, c2 = Cart('A'), Cart('B')
c1.add('apple')
print(c2.items) # ['apple']
items is a class attribute, so c1.items and c2.items are the same list. The fix is self.items = [] inside __init__, which binds a fresh list to each instance.
Traps
- Mutable class attributes shared across every instance.
- Forgetting to call the parent constructor in a subclass.
- Overriding a method with an incompatible signature.
- Confusing a class with an instance (
CartversusCart('A')). - Using inheritance where composition would be simpler.