A Level Computer 6: Introducing OOP
A Level Computer 6: Introducing OOP
ondon omputing
William Marsh
School of Electronic Engineering and Computer Science
Queen Mary University of London
Aims
• What and why OOP?
• The problem of software development
• OOP concepts
• Data hiding
• Class and instances
• Using classes in Python
• Using classes – example of files
• ‘Methods’ versus functions
• Create a new class in Python
What is OOP and
Why?
What is OOP?
• Object-oriented programming IS
• An idea for organising programs
Function def
• Discussion: is it obvious
what functions to choose? Function def
Main program
• Aside: more complex • Initialise
organisation possible variable
• Call functions
Exercise 1.1 (and 1.2)
• Use google to find an example of a failed
software project in the UK
• How late?
• How much money wasted?
OO Concepts
Data Hiding – Abstraction
• Different ways to represent complex data
• Example: shopping list
• List of pairs: (item string, amount integer)
• Dictionary: map from item to amount required
class Parameters in
def f1 Return value
def f2
class Parameters in
def f1
Return value
data
def f2
• File name
• Location of file on disk
• Buffer of text
def getAge(self):
return self.age
p1.setAge(21)
print(p1.getAge())
p2.setAge(101)
print(p2.getAge())
What is ‘self’?
• The name self is used by convention
• Not a key word
• Always use it
p1 = Person()
p2 = Person()
print(p1.getAge())
p1.setAge(21)
class Person:
def __init__(self, n):
self.name = n
self.age = 0
def getAge(self):
return self.age
Using a Constructor
• Constructor called using class name
p1 = Person("Alice")
p2 = Person("Bob")
print(p1.getAge())
p1.setAge(21)
• Guideline
• Write each class in a separate file
• Filename same as class name
• Import: