CST 445 M3
CST 445 M3
Module III
Object Oriented Programming
Python is a multi-paradigm programming language. It supports different programming
approaches.
One of the popular approaches to solve a programming problem is by creating objects.
This is known as Object-Oriented Programming (OOP).
Programming languages that allow the programmer to define new classes of objects are
called object-oriented languages. These languages also support a style of programming
called object-oriented programming.
In Python, the concept of OOP follows:
1. Class
2. Object
3. Method
4. Abstractions
5. Inheritance
6. Encapsulation
7. Polymorphism
Design with Classes
Like functions, objects are abstractions. A function packages an algorithm in a single
operation that can be called by name. An object packages a set of data values—its state—
and a set of operations—its methods—in a single entity that can be referenced with a
name. This makes an object a more complex abstraction than a function. To get inside a
function, you must view the code contained in its definition. To get inside an object, you
must view the code contained in its class. A class definition is like a blueprint for each of
the objects of that class. This blueprint contains
o Definitions of all of the methods that its objects recognize
o Descriptions of the data structures used to maintain the state of an object, or its
attributes, from the implementer’s point of view.
The class definition syntax has two parts: a class header and a set of method definitions that
follow the class header. The class header consists of the class name and the parent class name.
The class name is a Python identifier. The parent class name refers to another class. All Python
classes, including the built-in ones, are organized in a tree-like class hierarchy. At the top, or
root, of this tree is the most abstract class, named object, which is built in. Each class
immediately below another class in the hierarchy is referred to as a subclass, whereas the class
immediately above it, if there is one, is called its parent class. If the parenthesized parent class
name is omitted from the class definition, the new class is automatically made a subclass of
object.
Note that __init__ must begin and end with two consecutive underscores. This method is
also called the class’s constructor, because it is run automatically when a user
instantiates the class. Thus, when the code segment
o s = Student("Juan", 5)
is run, Python automatically runs the constructor or __init__ method of the Student class.
The purpose of the constructor is to initialize an individual object’s attributes.
Thus, for example, PhysicalObject would extend object, LivingThing would extend
PhysicalObject, and so on.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a class named Student, which will inherit the properties and methods from the
Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.
Use the Student class to create an object, and then execute the printname method:
class Student(Person):
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.
Note: The child's __init__() function overrides the inheritance of the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the parent's
__init__() function:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Python also has a super() function that will make the child class inherit all the methods
and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into the Student
class when creating student objects. To do so, add another parameter in the __init__()
function. Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
class Shape:
def __init__(self, name):
self.name = name
def area(self):
pass
def fact(self):
return "I am a two-dimensional shape."
def __str__(self):
return self.name
class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length
def area(self):
return self.length**2
def fact(self):
return "Squares have each angle equal to 90 degrees."
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
Output
Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985
Abstract Classes
An abstract class includes data and methods common to its subclasses, but is never
instantiated.
For example, checking accounts and savings accounts have similar attributes and
behavior. The data and methods that they have in common can be placed in an abstract
class named Account. The SavingsAccount and CheckingAccount classes can then
extend the Account class and access these common resources by inheritance.
Any special behavior or attributes can then be added to these two subclasses.
SavingsAccount and CheckingAccount are also known as concrete classes.
Unlike concrete classes, an abstract class such as Account is never instantiated(the object
of such class cannot be created).
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
Example:
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
First, the try clause (the statement(s) between the try and except keywords) is
executed.
If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then if its type matches the exception named after the except keyword,
the except clause is executed, and then execution continues after the try statement.
A try statement may have more than one except clause, to specify handlers for different
exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not in other
handlers of the same try statement.
An except clause may name multiple exceptions as a parenthesized tuple, for example: