Object-Oriented Programming Basics for A-Level Students

 
 
Session 2: Class Declaration
 
 
Object Oriented
Programming in A Level
 
Course
Outline
Recap of Week 1
Explored ideas of abstraction and decomposition
-
Many mechanisms for decomposition – e.g. functions, modules, classes
-
Decomposition needs practice – more than just learning the mechanisms
-
Guidance: decompose using abstractions
Emphasis on continuity of OOP
File: example of an abstractions
-
Hides information (e.g. location on disk)
File: example of using objects
-
Create an object – e.g. open function
-
Act on object – e.g. write method
Where objects /
classes come from?
How do I declare my
own classes?
 
Person versus Nearly Person
 
Two implementations
of an abstraction
-
OOP, using a class
-
Non-OOP, functions in
a module
 
Session Aim and Outline
 
Aims
 
Understand the difference
between classes and objects
Be able to write simple class
declarations, with constructor
Understand the difference
between objects and attributes
 
Outline
 
Recap modules and files
Declaring classes and methods
Discussion: Python Pro/Cons
Constructors and fields
Discussion: are classes easy to
find?
Collecting objects
 
 
 
 
Recap: Modules and Import
 
Organising a Python Program into Files
Python Modules
A module is a file containing function definitions (and statements)
If you import the module you can use the functions
Module name is file name
def f(name):
  return "hello "+ name
def g(i):
  return i+1
File lib.py
import lib
print(lib.f("bill"))
Import
Prefix
Import As
Module name prefix can be avoided
Import only some definitions
def f(name):
  return "hello "+ name
def g(i):
  return i+1
File lib.py
from lib import f
print(lib("bill"))
Import without prefix
No Prefix
 
The Person ‘Class’
 
Provide a Person class to use
… discuss implementation later
 
The Person Class
 
(Initially without
constructor)
File name is
 class name
class Person:
    # Initially, there is no constructor
 
    def setName(self, name):
        self.name = name
 
    def setJob(self, job):
        self.job = job
    def describe(self):
        s = "{0} works as a {1}"
        return s.format(self.name, self.job)
File Person.py
Defining a Method in a Class
class Person:
    # Initially, no constructor
    def setName(self, name):
        self.name = name
    def setJob(self, job):
        self.job = job
from Person import Person
p = Person()
p.setName("Bill")
p.setJob("plumber")
print(p.describe())
Two parameters
Parameter 1
Parameter 2
Name within
the object
Import: from 
file
import 
classname
person-ex1.py
 
Self
 
Self is NOT a keyword
ALWAYS use 'self'
 
To set a name in an
object of the Person
class ….
 … set the ‘name’ field
(or attribute) of the
object ….
… to the value given as a
parameter
class Person:
    # Initially, no constructor
 
    def setName(self, name):
        self.name = name
 
 
Attribute Getters and Setters
 
We can have a method
-
To set an attribute
-
To get the value of an attribute
 
WARNING
-
Do not always need getters and
setters
-
Not a good way to create
abstractions
class Person:
    # No constructor
 
    def setName(self, name):
        self.name = name
 
    def getName(self):
        return self.name
 
Practical Break
 
Task 1: Enhance the Person Class
Task 2: Create a new Pet Class
 
Discussion: What Are the
Pros/Cons for Python for
Teaching?
 
We teach programming principles
... we work with  specific language
Constructor
Before we can ‘act’ on an object
PROBLEM
-
New person is empty
-
Error if we describe
from Person import Person
p = Person()
p.setName("Bill")
p.setJob("plumber")
print(p.describe())
This is a default
constructor: it is
created
automatically
Defining a Constructor
Constructor
Has a special name
May have
parameters
Don’t forget ‘self’
class Person:
   def __init__(self, n):
      self.name = n
   def getName(self):
      return self.name
Constructor
name
Constructor
parameter
 
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 Person:
   def __init__(n):
      self.name = n
      self.job = "unknown"
      self.location = "unknown"
 
   def getName(self):
      return self.name
   def getJob(self):
      return self.job
   def getLocation(self):
      return self.location
Python Issues for Teaching 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
 
Practical Break
 
Task 3: Add a constructor
Task 4: Add getters
 
Finding Classes
 
Are classes ‘obvious’?
Two Examples: Find the Class, Object, Attributes
I have a red Ford car. It is a hatchback with 4 doors and 1600cc. Luckily it is petrol not
diesel. I prefer manual gearbox. My wife has a blue Merc: a coupe with 2 doors and
no space in the back. It is not very practical but she says that a 2.5litre engine feels
good and the automatic gearbox makes it easy to drive.
Have you seen the latest model from Jaguar, the XK5? You would never have
guessed that it’s a hybrid. I think that Charlie has a silver one. Anne has a new car
too, a Merc T2000, also in silver. I am not sure which is better: I like the look of the
Merc but of course the Jag uses less fuel – up to 65 mpg. Bill has one with the self-
driving features added – pricey, but he says it makes t much easier, given what a bad
driver he is.
 
Discussion: Finding Classes
 
Is the distinction between class, object and attribute
obvious in real-world?
 
Concepts
 
Potential Misunderstandings
 
Collecting Objects
 
We can put objects in lists
Must have the correct mental model for assignment
 
Collecting Object Example
 
Create a list of
people
Create two Person
objects
Add to list
from Person import Person
 
people = []
bill = Person("Bill")
people.append(bill)
clare = Person("Clare")
people.append(clare)
 
Collecting Object Example
 
Create a list of
people
Create two Person
objects
Add to list
 
Does this work?
Why no need to add
to list again?
 
from Person import Person
 
people = []
bill = Person("Bill")
people.append(bill)
clare = Person("Clare")
people.append(clare)
 
bill.setJob("plumber")
clare.setJob("programmer")
Understanding Python Assignment
 
Copy
-
Variable has value
-
Assignment copies value
Reference
-
Variable has reference
-
Assignment copies
reference
References 
 sharing
In Python
-
 All variables are references
-
But no difference when
immutable
name = Clare
job = programmer
name = Bill
job = plumber
 
Introduction to Homework
 
 
Care of Cats
 
Cats eat, sleep and (sometimes) purr
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 1
[P]at, [F]eed, [S]leep, [C]heck> p
Purrrrrrrr!
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 1
[P]at, [F]eed, [S]leep, [C]heck> p
Paws is tired. SCRATCHES you
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 1
[P]at, [F]eed, [S]leep, [C]heck> s
Paws goes to sleep
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 2
[P]at, [F]eed, [S]leep, [C]heck> p
Whiskers is tired. SCRATCHES you
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 2
[P]at, [F]eed, [S]leep, [C]heck> s
Whiskers goes to sleep
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 1
[P]at, [F]eed, [S]leep, [C]heck> c
Paws is asleep
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 1
[P]at, [F]eed, [S]leep, [C]heck> p
You have woken Paws
Paws is hungry. BITES you
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number> 2
[P]at, [F]eed, [S]leep, [C]heck> f
YOU ARE STUPID! Can't you see
Whiskers is asleep
Choose a cat:
  1: Paws
  2: Whiskers
  Cat number>
 
Cat Rules
 
Issues and Suggestions
 
Passage of Time
-
Behaviour depends on time (tired, hungry)
-
Time variable in interface – incremented on every interaction
-
Cat methods have time parameter
-
Cat class has some time attributes – e.g. time last woke up
Two files
-
Cat class and interface
Develop incrementally
-
Optional starter provide
-
Add features
More features – get more cats
 
Summary
 
 
Summary
 
We can create new classes
-
Methods
-
Constructor and attributes
Python issues: nothing declared
-
Enabled us to treat constructors second
Collecting objects
-
It works
-
… need to understand assignment and references
Slide Note
Embed
Share

Explore the fundamentals of object-oriented programming through class declaration, use of objects and methods, decomposition, abstraction, and more. Dive into topics like declaring classes, inheritance, polymorphism, and class diagrams. Gain insights into Python programming, modules, constructors, fields, and organizing programs into files. Enhance your understanding of classes, objects, attributes, and constructors to build a strong foundation in OOP.

  • OOP basics
  • Class declaration
  • Python programming
  • Abstraction
  • Inheritance.

Uploaded on Sep 22, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Object Oriented Programming in A Level Session 2: Class Declaration

  2. Course Outline Session Topics Use of objects and methods Decomposition and abstraction Aims of learning OOP Declaring classes Attributes, methods and the constructor Composition of classes Classes diagrams; visibility Inheritance, overriding and polymorphism More class diagrams Teaching issues Review and practical examples 1 2 3 4 5

  3. Recap of Week 1 Explored ideas of abstraction and decomposition - Many mechanisms for decomposition e.g. functions, modules, classes - Decomposition needs practice more than just learning the mechanisms - Guidance: decompose using abstractions Emphasis on continuity of OOP File: example of an abstractions - Hides information (e.g. location on disk) File: example of using objects - Create an object e.g. open function - Act on object e.g. write method Where objects / classes come from? How do I declare my own classes?

  4. Person versus Nearly Person Method / Example Description Two implementations of an abstraction - OOP, using a class - Non-OOP, functions in a module Person("John") p.setJob("brickie") Constructor for Person Set the job the person does p.setLocation("Sutton") Set the place p.setDriver(False) Set the driving status p.describe() Return a report string Method / Example Description newPerson("John") Constructor for Person setJob(p, "brickie") setLocation(p, "Sutton") Set the job the person does Set the place setDriver(p, False) Set the driving status describe(p) Return a report string

  5. Session Aim and Outline Aims Outline Understand the difference between classes and objects Be able to write simple class declarations, with constructor Understand the difference between objects and attributes Recap modules and files Declaring classes and methods Discussion: Python Pro/Cons Constructors and fields Discussion: are classes easy to find? Collecting objects

  6. Recap: Modules and Import Organising a Python Program into Files

  7. Python Modules A module is a file containing function definitions (and statements) If you import the module you can use the functions Module name is file name File lib.py def f(name): return "hello "+ name Import Prefix def g(i): return i+1 import lib print(lib.f("bill"))

  8. Import As Module name prefix can be avoided Import only some definitions File lib.py def f(name): return "hello "+ name Import without prefix No Prefix def g(i): return i+1 from lib import f print(lib("bill"))

  9. The Person Class Provide a Person class to use discuss implementation later

  10. Method / Example Description The Person Class p = Person Construct a new person p.setName("Bill") p.setJob("brickie") Set the person name Set the job the person does (Initially without constructor) File name is class name p.describe() Return a report string class Person: # Initially, there is no constructor def setName(self, name): self.name = name def setJob(self, job): self.job = job def describe(self): s = "{0} works as a {1}" return s.format(self.name, self.job) File Person.py

  11. Defining a Method in a Class class Person: # Initially, no constructor Two parameters Parameter 1 def setName(self, name): self.name = name Parameter 2 person-ex1.py def setJob(self, job): self.job = job from Person import Person p = Person() p.setName("Bill") p.setJob("plumber") print(p.describe()) Name within the object Import: from file import classname

  12. Self class Person: # Initially, no constructor Self is NOT a keyword ALWAYS use 'self' def setName(self, name): self.name = name To set a name in an object of the Person class . set the name field (or attribute) of the object . to the value given as a parameter

  13. Attribute Getters and Setters class Person: # No constructor We can have a method - To set an attribute - To get the value of an attribute def setName(self, name): self.name = name WARNING - Do not always need getters and setters - Not a good way to create abstractions def getName(self): return self.name

  14. Practical Break Task 1: Enhance the Person Class Task 2: Create a new Pet Class

  15. Discussion: What Are the Pros/Cons for Python for Teaching? We teach programming principles ... we work with specific language

  16. Constructor Before we can act on an object from Person import Person This is a default constructor: it is created automatically p = Person() p.setName("Bill") p.setJob("plumber") print(p.describe()) PROBLEM - New person is empty - Error if we describe

  17. Defining a Constructor class Person: def __init__(self, n): self.name = n Constructor Has a special name May have parameters def getName(self): return self.name Constructor name Constructor parameter Don t forget self

  18. Attributes Good Practice Attributes are not declared - In Python, nothing is! class Person: def __init__(n): self.name = n self.job = "unknown" self.location = "unknown" Good practice to initialise all attributes in the constructor - Getters do not fail - Clear what the attributes are - Do not add more def getName(self): return self.name def getJob(self): return self.job def getLocation(self): return self.location

  19. Python Issues for Teaching OOP Usual OOP Python The attributes are declared A class has a fixed set of attributes Attributes can be hidden: access only by methods 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

  20. Practical Break Task 3: Add a constructor Task 4: Add getters

  21. Finding Classes Are classes obvious ?

  22. Two Examples: Find the Class, Object, Attributes I have a red Ford car. It is a hatchback with 4 doors and 1600cc. Luckily it is petrol not diesel. I prefer manual gearbox. My wife has a blue Merc: a coupe with 2 doors and no space in the back. It is not very practical but she says that a 2.5litre engine feels good and the automatic gearbox makes it easy to drive. Have you seen the latest model from Jaguar, the XK5? You would never have guessed that it s a hybrid. I think that Charlie has a silver one. Anne has a new car too, a Merc T2000, also in silver. I am not sure which is better: I like the look of the Merc but of course the Jag uses less fuel up to 65 mpg. Bill has one with the self- driving features added pricey, but he says it makes t much easier, given what a bad driver he is.

  23. Discussion: Finding Classes Is the distinction between class, object and attribute obvious in real-world?

  24. Concepts Prerequisite? Knowledge? Calling? a? function? Variables? Concept? Calling? a? method? of? an? object.? Class? as? a? template? for? data:? what? the? object? knows .? Class? as? a? collection? of? methods:? what? the? object? does ? Constructors?Definition? and? use? of? constructors? Basic? mechanics? Functions? and? parameters? Functions? and? parameters? A? classes? represents? an? abstract? concept? in? the? problem? domain? Methods? have? parameters? Constructor? has? parameters? ? Abstraction? and? modelling? Class? declaration? and? construction? ?

  25. Potential Misunderstandings Misconception? Attributes? defined? or? referenced? in? the? wrong? scope.? Note:?use?of?self?is?mostly?done?by?following?rules?rather?than?a?deep?understanding.? Confusion? between? class? and? object? (or? instance)? created.? Confusion? that? nothing? happens.? Classes? always? have? only? a? single? instance? (object)? Possible?Evidence? Incorrect? use? of? self,? usually? omission.? ? The? program? is? run? without? any? objects? being? Inheritance? used? instead? of? object? creation:? e.g.? Bob? as? a? subclass? of? person? rather? than? an? instance.? ? Many? classes,? all? very? simple.? Confusion? between? class? and? attribute? Objects? only? contain? data? No? classes? with? methods? other? than? constructors? or? get? and? set.? ?

  26. Collecting Objects We can put objects in lists Must have the correct mental model for assignment

  27. Collecting Object Example Create a list of people Create two Person objects Add to list from Person import Person people = [] bill = Person("Bill") people.append(bill) clare = Person("Clare") people.append(clare)

  28. Collecting Object Example Create a list of people Create two Person objects Add to list from Person import Person people = [] bill = Person("Bill") people.append(bill) clare = Person("Clare") people.append(clare) Does this work? Why no need to add to list again? bill.setJob("plumber") clare.setJob("programmer")

  29. Understanding Python Assignment Copy - Variable has value - Assignment copies value Reference - Variable has reference - Assignment copies reference References sharing In Python - All variables are references - But no difference when immutable people = [ , ] name = Bill job = plumber name = Clare job = programmer clare = bill =

  30. Introduction to Homework

  31. Care of Cats Cats eat, sleep and (sometimes) purr Choose a cat: 1: Paws 2: Whiskers Cat number> 1 [P]at, [F]eed, [S]leep, [C]heck> p Purrrrrrrr! Choose a cat: 1: Paws 2: Whiskers Cat number> 1 [P]at, [F]eed, [S]leep, [C]heck> p Paws is tired. SCRATCHES you Choose a cat: 1: Paws 2: Whiskers Cat number> 1 [P]at, [F]eed, [S]leep, [C]heck> s Paws goes to sleep Choose a cat: 1: Paws 2: Whiskers Cat number> 2 [P]at, [F]eed, [S]leep, [C]heck> p Whiskers is tired. SCRATCHES you Choose a cat: 1: Paws 2: Whiskers Cat number> 2 [P]at, [F]eed, [S]leep, [C]heck> s Whiskers goes to sleep Choose a cat: 1: Paws 2: Whiskers Cat number> 1 [P]at, [F]eed, [S]leep, [C]heck> c Paws is asleep Choose a cat: 1: Paws 2: Whiskers Cat number> 1 [P]at, [F]eed, [S]leep, [C]heck> p You have woken Paws Paws is hungry. BITES you Choose a cat: 1: Paws 2: Whiskers Cat number> 2 [P]at, [F]eed, [S]leep, [C]heck> f YOU ARE STUPID! Can't you see Whiskers is asleep Choose a cat: 1: Paws 2: Whiskers Cat number>

  32. Cat Rules A Cat Can Eat When When it is awake Sleep When it is awake Pat (i.e. be patted) Anytime. If it is asleep, it wakes up. If it is hungry, it bites you; if it is tired it scratches you. Otherwise it purrrrrrs be tired If it has been awake for longer than it s last sleep be hungry If it has not been fed for a while

  33. Issues and Suggestions Passage of Time - Behaviour depends on time (tired, hungry) - Time variable in interface incremented on every interaction - Cat methods have time parameter - Cat class has some time attributes e.g. time last woke up Two files - Cat class and interface Develop incrementally - Optional starter provide - Add features More features get more cats

  34. Summary

  35. Summary We can create new classes - Methods - Constructor and attributes Python issues: nothing declared - Enabled us to treat constructors second Collecting objects - It works - need to understand assignment and references

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#