SlideShare a Scribd company logo
1 of 24
To Get Started
• Paper sheet
• Online:
www.eecs.qmul.ac.uk/~william/CAS-London-2018.html
• Download sample programs
• Create directory
• Unzip
• Recommend copy sample files before editing
Object Oriented
Programming in A
Level
Lecture 12
Session Aim and Outline
Outline
• Using classes: the Face
• Attributes and the constructor
• Reflection : Decomposition and
design
• Practical break
• Reflection: How versusWhy
• Progression
• Misconceptions
• Python versus java
Aims
• Be able to motivate the use of
classes and objects
• Be able to explain OOP in relations
Abstraction and Decomposition
• ...progression in OOP
• Be aware of issues for teaching
OOP
A Face Class: Becoming
a User of Objects
There are many examples of classes and object that are
familiar
from turtle import *
from Face import Face
f1 = Face(0, 0)
f1.draw()
f2 = Face(-200, 0)
f2.setSize(80)
f2.draw()
Using the Face Class
• File class
is a
familiar
example
• Are we
aware
we use
objects?
This is a variable. What is
the type of its value?
Draw methods:
which face is
drawn?
Objects and Methods
Name Type Description
F1, f2 Variables;
Objects of ‘Face’ class
A drawing of a face
Face Class name; constructor Create a Face object
setSize Method of ‘Face’ class Set size of the face
draw Method of ‘Face’ class Draw the face
‘Method’ is an OO word for function
Summary: Using Objects
• Face representation is hidden
• Method act (read or update) on objects
f2.setSize(80)
The object to be
acted on
The method:
implements the action
A second parameter:
the size to set
Teaching Functional Decomposition
• You have already learnt about functions
• How they work
• How to use them
• Is it easy or hard to learn about functions?
• What aspects are easier?
• What aspects are harder?
Reflection: Abstraction
and Decomposition
Motivation:What are we trying to achieve with classes?
Liskov and Guttag 1986 –
Decomposition
• A very small program consisting of no more than a few
hundred lines can be implemented as a single monolithic unit.
• However, as the size of the program increases such a ...
structure is no longer reasonable ...
• Instead the program must be decomposed into ... modules
that together provide the desired function.
• … how to decompose large programming problems into small
ones … what kinds of modules are useful … [how] modules can
be combined to solve the original problem
Two Different Aims for Learning
OOP
How
• How to use classes
• Create a new object
• Use objects as variables (e.g. in a
list)
• How to create (declare) new classes
• Add method and attributes
• … and constructors
• How to create sub-classes
(inheritance)
Why
• Decomposing a problem using
classes
• Which classes to use?
• What makes a good class?
• How to do good abstractions
• Analysis of the problem
• How classes can interact
• Software design
Summary
• Emphasis continuity between OOP and previous programming
• Use of objects and methods explained
• Abstractions implemented using functions
• Program decomposition; problem abstraction
• Distinguish between learning syntax and
• … practicing abstraction and program design
• OOP is a new solution to the goal of decomposition using abstraction
• Comparison with use of functions
DeclaringYour Own
Classes
Key concepts
The Faces Example
• Using Python turtle graphics
• Good points
• Visual and ?? Engaging (creative)
• Class versus object distinction
• Incremental
• Limitations
• Not typical of OO design
• Complexity of drawing a
distraction
from turtle import
class Face:
def __init__(self, xpos, ypos):
self.size = 50
self.coord = (xpos, ypos)
self.noseSize = 'normal'
def setSize(self, radius):
self.size = radius
def draw(self):
...
self.drawOutline()
...
Class Declaration
Constructor
Attributes
Method
def goHome(self):
penup()
goto(self.coord)
setheading(0)
def drawOutline(self):
penup()
forward(self.size)
left(90)
pendown()
circle(self.size)
self.goHome()
Defining a Constructor
Constructor
• Has a special
name
• May have
parameters
• Don’t forget ‘self’
class Face:
def __init__(self, xpos, ypos):
self.size = 50
self.coord = (xpos, ypos)
self.noseSize = 'normal'
Constructor
name
Constructor
parameter
Always ‘self’
Initialise
attributes
Attributes – Good Practice
• Attributes are not declared
• In Python, nothing is!
• Good practice to initialise
all attributes in the
constructor
• Getters do not fail
• Clear what the attributes
are
• Do not add more
class Face:
def __init__(self, xpos, ypos):
self.size = 50
self.coord = (xpos, ypos)
self.noseSize = 'normal'
def setSize(self, radius):
self.size = radius
PracticalWork
Drawing Faces
Program Structure and Complexity
• Program grows more
complex in structure
• Simpler elements remain
• If & loop  part of function
• Method  part of class
If &
loops
x =
while x > :
y =
print
class Friend:
def __init__()
def m1(a, b):
class Town:
def
__init__()
def m1(a, b):
Classes
&
objects Main program
• Create obj
• Call methods
Function
s
Function def
Function def
Main program
• Initialise vars
• Call functions
OOP
Concepts
Concept Details
Basic
mechanics
• Calling a method of an object
• Class as a template for data
• Class as a collection of methods
Constructors • Definition and use
Interaction • Object as a value (variable, list item, …)
• Object as an attribute value (has-a
relationship)
• Object passed as a parameter
Abstraction
and
modelling
• Class as a domain concept
• Methods (and constructor) have
parameters
Inheritance • Superclass and subclasses
• Constructor called using super()
• Method inherited or overridden
Prerequisit
e
knowledge:
functions &
parameters
Prerequisit
e
knowledge:
basic
mechanism
s
Misconception Possible Evidence
Attributes in the wrong scope • Omission of self (assignment or use)
Confusion between class and
object
• No objects created
• Only one instance
• Inheritance rather than instance
Confusion between class and
attribute
• Many classes – all simple
Objects only contain data • No encapsulation
• Only get and set methods
Objects do not interact • All code in single class
• Classes defined but not imported
• Objects not used as attributes
• Objects never passed as parameters
Believing objects are copied
not shared
• Unnecessary copying
• Unexpected sharing
Also lack of
prerequisit
e
knowledge:
functions &
parameters
Python Issues forTeaching OOP
Usual OOP
• The attributes are declared
• A class has a fixed set of attributes
• Attributes can be hidden: access
only by methods
Python
• Nothing is declared
• Attributes appear when assigned
to
• Hiding is not enforced
Use Python to teach OOP
• Avoid some Python tricks
• Use only a subset
• … explain later
Python versus Java
• No declarations
• Values are typed
• Variable types are
dynamic
• Run time type checking
• Syntax with indentation
• Permissive philosophy
• Declarations
• Static typing of variables
• Compile time type
checking
• Syntax with braces { }
• Rigid philosophy
Summary
• Object-oriented programming
• Builds on more basic programming
• A approach to program decomposition (decomposition take practice)
• Previous experience learning decomposition
• Progression: concepts not syntax
• Proficiency with functions essential
• Class versus object
• Classes have attributes and methods
• Constructor
• Relationships between classes; objects as values
• Inheritance
• Python – some disadvantages

More Related Content

Similar to Get Started with OOP Using the Face Class

The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptBill Buchan
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introductionmcollison
 
C++ in object oriented programming
C++ in object oriented programmingC++ in object oriented programming
C++ in object oriented programmingSaket Khopkar
 
PYTHON - OBJECT ORIENTED PROGRAMMING .pptx
PYTHON - OBJECT ORIENTED PROGRAMMING .pptxPYTHON - OBJECT ORIENTED PROGRAMMING .pptx
PYTHON - OBJECT ORIENTED PROGRAMMING .pptxSubashiniRathinavel
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
 
OOPs fundamentals session for freshers in my office (Aug 5, 13)
OOPs fundamentals session for freshers in my office (Aug 5, 13)OOPs fundamentals session for freshers in my office (Aug 5, 13)
OOPs fundamentals session for freshers in my office (Aug 5, 13)Ashoka R K T
 
Brief introduction to Object Oriented Analysis and Design
Brief introduction to Object Oriented Analysis and DesignBrief introduction to Object Oriented Analysis and Design
Brief introduction to Object Oriented Analysis and DesignAmrullah Zunzunia
 
Objected-Oriented Programming with Java
Objected-Oriented Programming with JavaObjected-Oriented Programming with Java
Objected-Oriented Programming with JavaOum Saokosal
 
Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP)Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP)Ahmad karawash
 

Similar to Get Started with OOP Using the Face Class (20)

The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in Lotuscript
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
Pi j1.0 workshop-introduction
Pi j1.0 workshop-introductionPi j1.0 workshop-introduction
Pi j1.0 workshop-introduction
 
C++ in object oriented programming
C++ in object oriented programmingC++ in object oriented programming
C++ in object oriented programming
 
OOP in JS
OOP in JSOOP in JS
OOP in JS
 
PYTHON - OBJECT ORIENTED PROGRAMMING .pptx
PYTHON - OBJECT ORIENTED PROGRAMMING .pptxPYTHON - OBJECT ORIENTED PROGRAMMING .pptx
PYTHON - OBJECT ORIENTED PROGRAMMING .pptx
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
OOPs fundamentals session for freshers in my office (Aug 5, 13)
OOPs fundamentals session for freshers in my office (Aug 5, 13)OOPs fundamentals session for freshers in my office (Aug 5, 13)
OOPs fundamentals session for freshers in my office (Aug 5, 13)
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
04 inheritance
04 inheritance04 inheritance
04 inheritance
 
The Big Picture
The Big PictureThe Big Picture
The Big Picture
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 
Brief introduction to Object Oriented Analysis and Design
Brief introduction to Object Oriented Analysis and DesignBrief introduction to Object Oriented Analysis and Design
Brief introduction to Object Oriented Analysis and Design
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
Objected-Oriented Programming with Java
Objected-Oriented Programming with JavaObjected-Oriented Programming with Java
Objected-Oriented Programming with Java
 
inheritance
inheritanceinheritance
inheritance
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
 
Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP)Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP)
 
Java
JavaJava
Java
 

Recently uploaded

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

Get Started with OOP Using the Face Class

  • 1. To Get Started • Paper sheet • Online: www.eecs.qmul.ac.uk/~william/CAS-London-2018.html • Download sample programs • Create directory • Unzip • Recommend copy sample files before editing
  • 2. Object Oriented Programming in A Level Lecture 12
  • 3. Session Aim and Outline Outline • Using classes: the Face • Attributes and the constructor • Reflection : Decomposition and design • Practical break • Reflection: How versusWhy • Progression • Misconceptions • Python versus java Aims • Be able to motivate the use of classes and objects • Be able to explain OOP in relations Abstraction and Decomposition • ...progression in OOP • Be aware of issues for teaching OOP
  • 4. A Face Class: Becoming a User of Objects There are many examples of classes and object that are familiar
  • 5. from turtle import * from Face import Face f1 = Face(0, 0) f1.draw() f2 = Face(-200, 0) f2.setSize(80) f2.draw() Using the Face Class • File class is a familiar example • Are we aware we use objects? This is a variable. What is the type of its value? Draw methods: which face is drawn?
  • 6. Objects and Methods Name Type Description F1, f2 Variables; Objects of ‘Face’ class A drawing of a face Face Class name; constructor Create a Face object setSize Method of ‘Face’ class Set size of the face draw Method of ‘Face’ class Draw the face ‘Method’ is an OO word for function
  • 7. Summary: Using Objects • Face representation is hidden • Method act (read or update) on objects f2.setSize(80) The object to be acted on The method: implements the action A second parameter: the size to set
  • 8. Teaching Functional Decomposition • You have already learnt about functions • How they work • How to use them • Is it easy or hard to learn about functions? • What aspects are easier? • What aspects are harder?
  • 9. Reflection: Abstraction and Decomposition Motivation:What are we trying to achieve with classes?
  • 10. Liskov and Guttag 1986 – Decomposition • A very small program consisting of no more than a few hundred lines can be implemented as a single monolithic unit. • However, as the size of the program increases such a ... structure is no longer reasonable ... • Instead the program must be decomposed into ... modules that together provide the desired function. • … how to decompose large programming problems into small ones … what kinds of modules are useful … [how] modules can be combined to solve the original problem
  • 11. Two Different Aims for Learning OOP How • How to use classes • Create a new object • Use objects as variables (e.g. in a list) • How to create (declare) new classes • Add method and attributes • … and constructors • How to create sub-classes (inheritance) Why • Decomposing a problem using classes • Which classes to use? • What makes a good class? • How to do good abstractions • Analysis of the problem • How classes can interact • Software design
  • 12. Summary • Emphasis continuity between OOP and previous programming • Use of objects and methods explained • Abstractions implemented using functions • Program decomposition; problem abstraction • Distinguish between learning syntax and • … practicing abstraction and program design • OOP is a new solution to the goal of decomposition using abstraction • Comparison with use of functions
  • 14. The Faces Example • Using Python turtle graphics • Good points • Visual and ?? Engaging (creative) • Class versus object distinction • Incremental • Limitations • Not typical of OO design • Complexity of drawing a distraction
  • 15. from turtle import class Face: def __init__(self, xpos, ypos): self.size = 50 self.coord = (xpos, ypos) self.noseSize = 'normal' def setSize(self, radius): self.size = radius def draw(self): ... self.drawOutline() ... Class Declaration Constructor Attributes Method def goHome(self): penup() goto(self.coord) setheading(0) def drawOutline(self): penup() forward(self.size) left(90) pendown() circle(self.size) self.goHome()
  • 16. Defining a Constructor Constructor • Has a special name • May have parameters • Don’t forget ‘self’ class Face: def __init__(self, xpos, ypos): self.size = 50 self.coord = (xpos, ypos) self.noseSize = 'normal' Constructor name Constructor parameter Always ‘self’ Initialise attributes
  • 17. Attributes – Good Practice • Attributes are not declared • In Python, nothing is! • Good practice to initialise all attributes in the constructor • Getters do not fail • Clear what the attributes are • Do not add more class Face: def __init__(self, xpos, ypos): self.size = 50 self.coord = (xpos, ypos) self.noseSize = 'normal' def setSize(self, radius): self.size = radius
  • 19. Program Structure and Complexity • Program grows more complex in structure • Simpler elements remain • If & loop  part of function • Method  part of class If & loops x = while x > : y = print class Friend: def __init__() def m1(a, b): class Town: def __init__() def m1(a, b): Classes & objects Main program • Create obj • Call methods Function s Function def Function def Main program • Initialise vars • Call functions
  • 20. OOP Concepts Concept Details Basic mechanics • Calling a method of an object • Class as a template for data • Class as a collection of methods Constructors • Definition and use Interaction • Object as a value (variable, list item, …) • Object as an attribute value (has-a relationship) • Object passed as a parameter Abstraction and modelling • Class as a domain concept • Methods (and constructor) have parameters Inheritance • Superclass and subclasses • Constructor called using super() • Method inherited or overridden Prerequisit e knowledge: functions & parameters Prerequisit e knowledge: basic mechanism s
  • 21. Misconception Possible Evidence Attributes in the wrong scope • Omission of self (assignment or use) Confusion between class and object • No objects created • Only one instance • Inheritance rather than instance Confusion between class and attribute • Many classes – all simple Objects only contain data • No encapsulation • Only get and set methods Objects do not interact • All code in single class • Classes defined but not imported • Objects not used as attributes • Objects never passed as parameters Believing objects are copied not shared • Unnecessary copying • Unexpected sharing Also lack of prerequisit e knowledge: functions & parameters
  • 22. Python Issues forTeaching OOP Usual OOP • The attributes are declared • A class has a fixed set of attributes • Attributes can be hidden: access only by methods Python • Nothing is declared • Attributes appear when assigned to • Hiding is not enforced Use Python to teach OOP • Avoid some Python tricks • Use only a subset • … explain later
  • 23. Python versus Java • No declarations • Values are typed • Variable types are dynamic • Run time type checking • Syntax with indentation • Permissive philosophy • Declarations • Static typing of variables • Compile time type checking • Syntax with braces { } • Rigid philosophy
  • 24. Summary • Object-oriented programming • Builds on more basic programming • A approach to program decomposition (decomposition take practice) • Previous experience learning decomposition • Progression: concepts not syntax • Proficiency with functions essential • Class versus object • Classes have attributes and methods • Constructor • Relationships between classes; objects as values • Inheritance • Python – some disadvantages