S20 · Computer Studies II · Grade 11 · ages 16–17
OOP in Python
Writing classes, objects and class relationships
Grade 11 · 3.2 Object Oriented Programming ImplementationCBE strandFree · works offline
▶ Start the interactive lessonThe full lesson adds narration, an interactive mission and a 10-question bank, and the quiz explains any mistakes.
Declaring a class
In Python, a class starts with class Student: and its methods go indented underneath. The special method __init__ is the constructor: it runs when a new object is made and sets its starting attributes, for example self.name = name. self means "this particular object".
Creating and using objects
s = Student("Amani", 1021) creates an object and calls __init__ for you. Use a dot to reach its parts: s.name gives "Amani", and s.greet() calls a method. Each object keeps its own attribute values, so another Student("Wanjiru", 1022) has a different name.
Instance and class (static) variables
Instance variables belong to one object (self.name). Class variables are shared by every object of the class, declared directly inside the class: school = "Kenya High". Java and C++ call these static variables. Change a class variable and every object sees the new value.
Visibility
Java and C++ use the keywords public, private and protected to control who can use an attribute. Python uses naming conventions instead: name is public, _name means protected (for this class and its children), and __name means private, and Python hides it from outside code. Good programs keep data private and expose methods.
Relationships between classes
Inheritance: class Teacher(Person): makes Teacher a kind of Person (an "is-a" link). Association: a Teacher teaches Students, but each exists separately. Aggregation: a Department has Teachers, who could exist without it. Composition: a House has Rooms that cannot exist without the house; delete the house and the rooms go too.
Key points
- A class starts with the word class, and its methods are indented underneath.
- The constructor, underscore underscore init, sets up each new object.
- self means this particular object.
- Instance variables belong to one object; class variables are shared by all.
- Python marks protected with one underscore and private with two.
- class Teacher(Person) means Teacher inherits from Person.
- Association uses, aggregation has, and composition owns completely.
Try it for real: Code a class
- If you can, open Python and write a BankAccount class with a balance, a deposit(amount) method, and a withdraw(amount) method that refuses to go below zero.
- Create two accounts, deposit into one, and print both balances to show that each object keeps its own data.