Edexcel International Advanced Level Computer Science, point 20.1.1
The concepts of OOP are in 13.1.1, including UML class diagrams. In Unit 4 you must write the code: convert a UML class diagram into Python, and select and use OOP features. Check the Programming Language Subset (PLS) for the syntax allowed.
a to d: classes, attributes, methods and objects
class Student: # a. class
def __init__(self, name, form): # the constructor
self.name = name # b. attributes
self.form = form
self.marks = []
def add_mark(self, mark): # c. a method
self.marks.append(mark)
def average(self): # c. another method
if not self.marks:
return 0
return sum(self.marks) / len(self.marks)
amy = Student("Amy", "12A") # d. objects (instances)
raj = Student("Raj", "12B")
amy.add_mark(70)
amy.add_mark(90)
print(amy.average(), raj.average()) # 80.0 0
selfis the object the method is called on.- Each object has its own attributes.
__init__runs when an object is created.- Class attributes (shared by all objects) are defined in the class body:
class Student:
school = "Greenfield" # a class attribute, shared
e. Encapsulation, f. getters, g. setters
Make attributes private (a leading double underscore) and give controlled access through methods.
class Thermostat:
def __init__(self, room, target=20):
self.room = room
self.__target = target # private: name mangling
def get_target(self): # f. getter
return self.__target
def set_target(self, degrees): # g. setter, with validation
if degrees < 5 or degrees > 30:
raise ValueError("target must be 5 to 30")
self.__target = degrees
def warmer(self):
self.set_target(self.__target + 1) # reuses the validation
t = Thermostat("Lounge", 21)
t.warmer()
print(t.get_target()) # 22
# t.__target -> AttributeError: not accessible directly
Python's @property is a neat alternative that gives attribute-style access with the same control:
class Circle:
def __init__(self, radius):
self.radius = radius # uses the setter below
@property
def radius(self): # getter
return self._radius
@radius.setter
def radius(self, value): # setter, with validation
if value <= 0:
raise ValueError("radius must be positive")
self._radius = value
c = Circle(2)
# looks like an attribute, but is validated
c.radius = 5
print(c.radius) # 5
Benefits of encapsulation: invalid data can't get in, the inside can change without affecting other code, and errors are easier to trace.
h. Aggregation and i. composition
Both are "has-a" relationships (an object contains other objects).
- Aggregation: the parts can exist independently of the whole (a team has players; players exist without the team).
- Composition: the parts belong to the whole and are created and destroyed with it (a house has rooms).
class Player:
def __init__(self, name):
self.name = name
# AGGREGATION: players exist separately
class Team:
def __init__(self, name, players):
self.name = name
# existing objects are passed in
self.players = players
class Engine:
def start(self):
return "Engine running"
# COMPOSITION: Car creates its Engine
class Car:
def __init__(self):
self.engine = Engine() # the Engine is created here
def start(self):
return self.engine.start()
p1, p2 = Player("Amy"), Player("Raj")
team = Team("Lions", [p1, p2]) # p1 and p2 outlive the team
print(Car().start()) # Engine running
UML: a hollow diamond for aggregation, a filled diamond for composition (13.1.1).
j. Inheritance
A subclass takes on a superclass's attributes and methods, and adds or overrides.
class Person:
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name}"
class Teacher(Person): # Teacher IS-A Person
def __init__(self, name, subject):
# run the parent's constructor
super().__init__(name)
self.subject = subject
# overrides the parent's method
def describe(self):
return f"{super().describe()}, teaches {self.subject}"
t = Teacher("Ms Cho", "Computing")
print(t.describe()) # Ms Cho, teaches Computing
k. Polymorphism
The same method call does different things for different classes, so code can treat different objects the same way.
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r ** 2
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
shapes = [Circle(1), Rectangle(2, 3)]
for s in shapes:
print(round(s.area(), 2)) # 3.14 then 6
print(sum(s.area() for s in shapes)) # no type checks needed
Converting a UML class diagram into code
Rules for the conversion:
| UML | Python |
|---|---|
| Class box | class Name: |
+ public attribute or method |
name |
# protected |
_name |
- private |
__name |
| Attribute type | Set in __init__ (and validated if needed) |
| Method | def name(self, ...) |
| Inheritance arrow | class Car(Vehicle): |
| Composition or aggregation | An attribute holding other objects |
class Vehicle:
def __init__(self, reg):
self._reg = reg # # protected
self.__speed = 0 # - private
def accelerate(self, amount): # + public
self.__speed += amount
def get_speed(self): # + public
return self.__speed
class Car(Vehicle):
def __init__(self, reg, doors):
super().__init__(reg)
self.__doors = doors # - private
def open_door(self):
return f"Opening one of {self.__doors} doors"
def describe(self):
return f"Car {self._reg}, speed {self.get_speed()}"
c = Car("AB12 CDE", 4)
c.accelerate(30)
print(c.describe(), "|", c.open_door())
Output: Car AB12 CDE, speed 30 | Opening one of 4 doors.
Special methods (for interest)
__str__ gives a readable string, __eq__ defines ==, __len__ defines len():
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2), Point(1, 2) == Point(1, 2)) # (1, 2) True
Worked example
Task: a school system has Person (name), Student (inherits, adds a form and marks, with a validated add_mark), and School (holds a list of students). Write the classes and show polymorphism.
class Person:
def __init__(self, name):
self.name = name
def role(self):
return "person"
class Student(Person):
def __init__(self, name, form):
super().__init__(name)
self.form = form
self.__marks = [] # encapsulated
def add_mark(self, mark):
if not 0 <= mark <= 100:
raise ValueError("mark must be 0 to 100")
self.__marks.append(mark)
def average(self):
if not self.__marks:
return 0
return sum(self.__marks) / len(self.__marks)
def role(self): # overrides: polymorphism
return "student"
class School:
def __init__(self):
# aggregation: holds Person objects
self.people = []
def add(self, person):
self.people.append(person)
school = School()
amy = Student("Amy", "12A")
amy.add_mark(80)
amy.add_mark(90)
school.add(amy)
school.add(Person("Mr Lee"))
for p in school.people:
# Amy student / Mr Lee person
print(p.name, p.role())
print(amy.average()) # 85.0
OOP features used: classes, objects, attributes and methods, encapsulation (private __marks, with add_mark validating), inheritance (Student(Person)), polymorphism (role()), and aggregation (School holds Person objects).
Exam tip: convert UML carefully (visibility symbols, types, the inheritance arrow). Use super().__init__() in a subclass constructor. Validate in setters. Name the OOP feature you are using if asked, and say why it helps (encapsulation protects data; polymorphism avoids type checks).
Check yourself
What is the purpose of a setter?
To change a private attribute in a controlled way, validating the new value first.
What is the difference between aggregation and composition?
In aggregation the parts can exist independently of the whole; in composition the parts belong to the whole and are created and destroyed with it.
Why call super().__init__() in a subclass constructor?
To run the parent class's constructor so the inherited attributes are set up.
How does a UML private attribute (-) appear in Python?
With a leading double underscore, such as self.__speed.
Give an example of polymorphism
Calling area() on a list of different shapes, where each class supplies its own version of the method.