Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

IS5312 Week 9:

Object-Oriented
Programming
Classes and Objects
• Programs grow in size, become more complex,
• Number of programmers working on same project increases
• A small change made by one programmer in one place may have
unintended effects in other places

• Dependencies and interrelationships throughout code


increases
Classes and Objects
• Partial solution to this problem is data hiding
• Within a program, as much implementation detail as possible is hidden
• An object is an encapsulation of data and methods that act on the
data.
• Programmer using an object is concerned only with
• Tasks that the object can perform
• Parameters used by these tasks
Classes
• Classes are templates from which objects are created
• Specifies properties, methods that will be common to all objects, instances
of that class

• Classes can be
• Typed directly into programs
• Stored in modules and brought into programs with an import statement
Built-in Classes
• All strings are instances of the class str, and all lists are
instances of the class list.
• Although each string holds its own value, all strings have the
same methods. Similarly, all lists have the same methods.
• We will refer to the data types str, int, float, list, tuple,
dictionary, and set as built-inPython classes.
• We will refer to a specific literal from one of these classes as
an instance of the class.

• “Hello World!” is an object of Class str.


• [1, 2, 3] is an object of Class list.
User-defined Classes
• Each class defined by users will have a specified set of methods

• Each instance(object) of the class will have its own value(s)


A typical class definition
User-defined Classes
• The __init__ method (also known as the constructor) is automatically called
when an object is created. It creates and assigns values to the instance variables
that store the values for the object.

• Instance variables are also called the properties of the class, and the collections
of values of the instance variables are called the state of the object.

• Methods are defined much like ordinary functions


• Methods have self as their first parameter.
• When an object (instance of the class) is created, each method’s self parameter references
the object so that the method knows which object to operate on.
Why classes?
Example 1: Class of rectangles
The Rectangle class can set and get measurements of rectangle
In- class exercise 1—define your own
class
Further define the class Rectangle. Your program should creat a rectangle object with given
width and height, then calls getWidth(), getHeight(), Area(), Perimeter(). Given the following
main program, the output should be as follows:

12
IS5312 - CityU WK10_OOP
Traditional way vs class
Example 2: Class of students
Example 3: Class of Employees
• Define a class of employees with their first name and last names and
two methods:
• initial: the first letters of the first and last names
• number_letter: count the total number of letters in their names.
• The class should be capable of the following. Upload the .py file and
the output screenshot on Canvas.
class Employee:

def __init__(self, first, last):


self.first = first
self.last = last

def initial(self):
return self.first[0]+self.last[0]

def number_letter(self):
return len(self.first)+len(self.last)

Some slides from © 2016 Pearson Education, Ltd. All rights reserved.
In-class exercise 2- list of objects
1.Revise the definition of class Rectangle you just created. You don’t give any data when you
create Rectangle objects. You should define setWidth() and setHeight() to populate objects.
Then, Create a list of 20 rectangle objects. Use data generation to populate your rectangles
and then display the object’s details.

IS5312 - CityU WK10_OOP 1


6
Calling with the class name
Class variable
• The first and last variables in the previous examples are called
instance variables – the value varies from instance(object) to instance
(object).

• A class variable is a variable that is shared among all instances in the


class.
Example 4: class variable
Inheritance
Inheritance
• Inheritance allows us to define a new class
• Called the subclass, child class, or derived class
• A modified version of an existing class (called the superclass, parent class, or
base class).

• Subclass inherits properties and methods of the superclass


• Adding some of its own properties and methods
• Overriding some of the superclass' methods
Subclass
Example 5
issubclass
The "is-a" Relationship
• Child classes are specializations of their parent's class
• Have all the characteristics of their parents
• But more functionality
• Each child satisfies the "is-a" relationship with the parent
The isinstance Function
isinstance
Overriding a Method
• If method defined in subclass has the same name as a method in its
superclass
• Child's method will override parent's method
In-class exercise 3- Inheritance of class

• Given the below Vehicle class and Bus class, define a fare function for class Vehicle
and overload it in the bus class. The default fare charge of any vehicle is seating
capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as
a maintenance charge. Also add __str__ function to both Vehicle and Bus to display
the object details of each class. Create an object of Bus and display the object details
similar as follows:
In-class-Exercise 4-Use OOP to process words

Use both non-OOP approach and OOP approach to create a program that counts and display the letter
frequencies as above.
1. Define a dictionary with unique letters as key and frequencies as value. Convert this dictionary to a list
of pairs of letter-frequency then sort the list by frequency using a lambda function then display the
letters and frequencies one by one in descending order.

2. Define a class Words_parser for the same purpose. Your class should contain a few functions such as: a
sentence() that takes input from the user and create a dictionary to store the letters and associated
frequencies, a sortF() function that sorts the letters by frequency in descending order, a display() function
to display letters and frequencies.
Finally, define a main function to create an object and call the functions.

IS5312 - CityU WK10_OOP 22

You might also like