0% found this document useful (0 votes)
13 views

Object Oriented Programming OOP (Autosaved)

Uploaded by

Trynos
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Object Oriented Programming OOP (Autosaved)

Uploaded by

Trynos
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Object Oriented

Programming OOP
Concept of OOP
• OOP groups together the record data structure and the subroutines
that operate on the data items in this data structure.
• Such a group is called an 'object'.
• The feature of data being combined with the subroutines acting on the
data is known as encapsulation.
• To use an object, we first define an object type. An object type is called
a class.
• Encapsulation: combining data and subroutines into a class
• Class: a type that combines a record with the methods that operate on
the properties in the record
Example of a record
• A car manufacturer and seller wants to store details about cars.
• These details can be stored in a record structure
TYPE CarRecord
DECLARE VehicleID PROCEDURE UpdateRegistration(BYREF ThisCar :
DECLARE Registration CarRecord, BYVAL NewRegistration)
DECLARE DateOfRegistration ThisCar.Registration NewRegistration
DECLARE EngineSize END PROCEDURE
DECLARE PurchasePrice
END TYPE
• We can call this procedure from anywhere in our program.
• we can also access the record fields directly from anywhere within the scope of ThisCar:

ThisCar.EngineSize🡨 2500
Classes in OOP
• OOP group together the data structure and subroutine that operate on
the data items in this structure
• Such a group is called an object
• Data of an object are called attributes and the subroutines acting on the
attributes are called methods
Classes in OOP
• The idea behind classes in OOP is that attributes can only be accessed
through methods
• The path to data is unavailable
• Attributes are referred to as 'private'.
• The methods to access the data are made available to programmers, so
these are 'public'.
• Classes are templates for objects.
• When a class type has been defined it can be used to create one or
more objects of this class type
• Therefore an object are instances of a class
New vocabulary
• Attributes: the data items of a class
• Methods: the subroutines of a class
• Object: an instance of a class
• Encapsulation: combining data and subroutine into a class and
restricting external access to the data
Advantages of OOP over procedural languages

• The advantage of OOP is that it produces robust, more reliable code.


• The attributes can only be manipulated using methods provided by
the class definition.
• This means the attributes are protected from accidental changes.
• Classes provided in module libraries are thoroughly tested .
• If you use tried and tested building blocks to construct your program,
you are less likely to introduce bugs than when you write code from
scratch.
Designing classes and objects

• When designing a class, identify the attributes we want to store.


• We also need to think about the methods we need to access the data
and assign values to the data of an object.
• A class definition is a blueprint when declaring an object of that class.
• Creating a new object is known as 'instantiation'.
• Any data that is held about an object must be accessible, otherwise
there is no point in storing it.
• We therefore need methods to access each one of these attributes.
• Those method are referred as getters
Designing classes and objects
• When we first set up an object of a particular class, we use a
constructor.
• A constructor instantiates the object and assigns initial values to the
attributes.
• Any properties that might be updated after instantiation will need
subroutines to update their values.
• These are referred to as setters.

Constructor: a special type of method that is called to create a new


object and initialise its attributes
New vocabulary
Getter: a method to access its associated attribute
Constructor: a special type of method that is called to create a new
object and initialise its attribute
Setter: a method to set the value of its associated attribute
Class Definition Syntax
• The simplest form of class definition looks like this

class ClassName:
<statement-1>
.
.
.
<statement-N>
Class Objects
• Class objects support two kinds of operations: attribute references and instantiation.
• Attribute references use the standard syntax used for all attribute references in Python: obj.name.
• So, if the class definition looked like this:

class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'

• then MyClass.i and MyClass.f() are valid attribute references, returning an


integer and a function object, respectively.
• Class attributes can also be assigned to, so you can change the value
of MyClass.i by assignment
Class instantiation
• Class instantiation uses function notation.
• Just pretend that the class object is a parameterless function that returns a new
instance of the class.
• For example (assuming the above class):

x = MyClass()

• creates a new instance of the Myclass and assigns this object to the local variable x.
Initialising class object
• The instantiation operation (“calling” a class object) creates an empty object.
• Many classes like to create objects with instances customized to a specific initial state.
• Therefore a class may define a special method named __init__(), like this:

def __init__(self):
self.data = []

• This method is referred to as constructor


• Constructor: a special type of method that is called to create a new object and
initialise its attributes
• When a class defines an __init__() method, class instantiation automatically invokes
__init__() for the newly-created class instance.
Initialising class object

class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
Creating a class
• When a car is manufactured it is given a unique vehicle ID that will remain the same
throughout the car's existence.
• The engine size of the car is fixed at the time of manufacture.
• The registration ID will be given to the car when the car is sold .
• In our program, when a car is manufactured, we want to create a new car object.
• We need to instantiate it using the constructor.
• Any attributes that are already known at the time of instantiation can be set with the
constructor.
• In our example, vehicle ID and Enginesize can be set by the constructor.
• The other attributes are assigned values at the time of purchase and registration.
• So we need setters for them. The identifier table for the car class is shown in Table 27.01.
Creating class
We can represent this information as a class diagram
Writing object-oriented code
Declaring a class
• Attributes should always be declared as 'Private'.
• This means they can only be accessed through the class methods.
• So that the methods can be called from the main program, they have
to be declared as 'Public'.
• Python include the method body within the class declaration.
Instantiating a class

• To use an object of a class type in a program the object must first be


instantiated .
• This means the memory space must be reserved to store the
attributes.
• The following code instantiates an object Thiscar of class car.

ThisCar = Car( "ABC123 4" , 2500)


Using a method
• To call a method in program code, the object identifier is followed by
the method identifier and the parameter list.
• The following code sets the purchase price for an object Thiscar of
class car.
This Car. SetPurchasePrice (12000)
• The following code gets and prints the vehicle ID for an object Thiscar
of class car.

print (ThisCar.GetVehicleID ())


Inheritance
Inheritance is the process by which the methods and data from one
class, a superclass or base class, are copied to another class, a derived
class.
Inheritance
• The advantage of OOP is that we can design a class (a base class or a
superclass) and then derive further classes (subclasses) from this base
class.
• This means that we write the code for the base class only once and
the subclasses make use of the attributes and methods of the base
class, as well as having their own attributes and methods.
• This is known as inheritance and can be represented by an
inheritance diagram
Diagram showing inheritance
Diagram showing inheritance
New vocabulary
• Inheritance: all attributes and methods of the base class are copied to
the subclass
Inheritance
class baseclass:
<statement-1>
.
.
.
<statement-N
class subclass(BaseClass):
<statement-1>
.
.
.
<statement-N>
Example
❖ A base class employee and the derived classes partTime and
fullTime are defined.

❖ The objects permanentStaff and temporaryStaff are instanced


in these examples and use the method showDetails.
Base class
class employee:
def __init__ (self, name, staffno):
self.__name = name
self.__staffno = staffno
self.__fullTimeStaff = True
def showDetails(self):
print("Employee Name " + self.__name)
print("Employee Number " , self.__staffno)
Derived class
class partTime(employee):
def __init__(self, name, staffno):
employee.__init__(self, name, staffno)
self.__fullTimeStaff = False
self.__hoursWorked = 0
def getHoursWorked (self):
return(self.__hoursWorked)
Derived Class
class fullTime(employee):
def __init__(self, name, staffno):
employee.__init__(self, name, staffno)
self.__fullTimeStaff = True
self.__yearlySalary = 0
def getYearlySalary (self):
return(self.__yearlySalary)
Class diagram
Whole program
Implementing a library system
• Consider the following problem:
• A college library has items for loan.
• The items are currently books and CDs.
• Items can be borrowed for three weeks.
• If a book is on loan, it can be requested by another
borrower.
• Note that we could have a variable Title, which
stores the book title or the CD title, depending on
which type of library item we are working with.
• There are further similarities (marked* in Table ).
• There are some items of data that are different
for books and CDs.
• Books can be requested by a borrower. For CDs,
the genre is to be stored.
Implementing a library system

• We can define a class Libraryitem and derive a Book class and a CD


class from it.
• We can draw the inheritance diagrams for the Libraryitem, Book and
CD classes as in diagram below
Implementing a library system
• Analysing the attributes and methods required for all library items
and those only required for books and only for CDs, we arrive at the
class diagram
Implementing a library system
• A base class that is never used to create objects directly is known as
an abstract class.
• Libraryitem is an abstract class.
• Abstract class: a base class that is never used to create objects
directly
Declaring a base class and derived classes (subclasses) in Python

• The code below shows how a base class and its subclasses are declared in
Python.
Declaring a base class and derived classes (subclasses) in Python
Instantiating a subclass
• Creating an object of a subclass is done in the same way as with any
class
ThisBook = Book(Title, Author, ItemID)
ThisCD = CD (Title, Artist, ItemID)

Using a method
• Using an object created from a subclass is exactly the same as an
object created from any class.
Multiple Inheritance

• Python supports a form of multiple


inheritance as well.
• A class definition with multiple base classes
looks like this
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Multilevel inheritance
• On the other hand, we can also inherit form a derived class.
• This is called. multilevel inheritance.
• In multilevel inheritance, features of the base class and the
derived class is inherited into the new derived class.
• An example with corresponding visualization is given below
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Polymorphism in Python
• Polymorphism: the method behaves differently for different classes in
the hierarchy
• Polymorphism is an important feature of class definition in Python
that is utilized when you have commonly named methods across
classes or subclasses.
• When several classes or subclasses have the same method names,
but different implementations for these same methods, the classes
are polymorphic because they are using a single interface to use with
entities of different types
Garbage collection
• When objects are created they occupy memory.
• When they are no longer needed, they should be made to release
that memory, so it can be re -used.
• If objects do not let go of memory, we eventually end up with no free
memory when we try and run a program.
• This is known as 'memory leakage'.
• Memory management involves a private heap containing all Python
objects and data structures.
• The management of the Python heap is performed by the interpreter
itself.
• The programmer does not need to do any housekeeping.
Containment (aggregation)
• we covered how a subclass inherits from a base class.
• This can be seen as generalisation and specialisation.
• The base class is the most general class, subclasses derived from this
base class are more specialised
• Containment means that one class contains other classes.
• Containment: a relationship in which one class has a component that
is of another class type
Example
• a car is made up of different parts and each part will be an object
based on a class.
• The wheels are objects of a different class to the engine object.
• The engine is also made up of different parts.
• Together, all these parts make up one big object.
Example of containment
• A college runs courses of up to 50 lessons. A course may end with an assessment.
• Object oriented programming is to be used to set up courses. The classes required are shown in
Example of containment
Python Course class declaration

class Course:
def __init__(self, t, m): # sets up a new course
self.__CourseTitle = t
self.__MaxStudents = m
self.__NumberOfLessons = 0
self.__CourseLesson = []
self.__CourseAssessment = Assessment
def AddLesson(self, t, d, r):
self.__NumberOfLessons = self.__NumberOfLessons + 1
self.__CourseLesson.append(Lesson(t, d, r))
def AddAssessment(self, t, m):
self.__CourseAssessment = Assessment(t, m)
def OutputCourseDetails(self):
print(self.__CourseTitle, "Maximum number: ", self.__MaxStudents)
for i in range(self.__NumberOfLessons):

You might also like