0% found this document useful (0 votes)
138 views16 pages

CST 445 M3

This document discusses object-oriented programming in Python. It covers key concepts like classes, objects, methods, inheritance, encapsulation, and polymorphism. It provides examples of defining a Student class with attributes like name and test scores, and methods like getScore() and __str__() to access and represent an object's state. Inheritance is demonstrated by creating subclasses that inherit from the Person class.

Uploaded by

shyam krishnan s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views16 pages

CST 445 M3

This document discusses object-oriented programming in Python. It covers key concepts like classes, objects, methods, inheritance, encapsulation, and polymorphism. It provides examples of defining a Student class with attributes like name and test scores, and methods like getScore() and __str__() to access and represent an object's state. Inheritance is demonstrated by creating subclasses that inherit from the Person class.

Uploaded by

shyam krishnan s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CST 445: Python for Engineers

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.

Downloaded from Ktunotes.in


The syntax of a simple class definition is the following:

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.

The example code for the Student class follows:

Downloaded from Ktunotes.in


The next session shows how the class could be used:

Downloaded from Ktunotes.in


Method Definitions
 All of the method definitions are indented below the class header. Because methods are a
bit like functions, the syntax of their definitions is similar.
 Each method definition must include a first parameter named self, even if that method
seems to expect no arguments when called.
 When a method is called with an object, the interpreter binds the parameter self to that
object so that the method’s code can refer to the object by name.
 Thus, for example, the code
o s.getScore(4)
 binds the parameter self in the method getScore to the Student object referenced by the
variable s. The code for getScore can then use self to access that individual object’s test
scores.
 Otherwise, methods behave just like functions. They can have required and/or optional
arguments and they can return values. They can create and use temporary variables. A
method automatically returns the value None when it includes no return statement.

The __init__ Method and Instance Variables


 Most classes include a special method named __init__.
 Here is the code for this method in the Student class:

 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.

Downloaded from Ktunotes.in


 In addition to self, the Student constructor expects two arguments that provide the initial
values for these attributes.
 The attributes of an object are represented as instance variables.
 Each individual object has its own set of instance variables. These variables serve as
storage for its state.
 The scope of an instance variable (including self) is the entire class definition.
 Thus, all of the class’s methods are in a position to reference the instance variables.
 The lifetime of an instance variable is the lifetime of the enclosing object.
 Within the class definition, the names of instance variables must begin with self.

The __str__ Method


 Many built-in Python classes usually include an __str__ method.
 This method builds and returns a string representation of an object’s state.
 When the str function is called with an object, that object’s __str__ method is
automatically invoked to obtain the string that str returns.
 For example, the function call str(s) is equivalent to the method call s.__str__(), and is
simpler to write.
 The function call print(s) also automatically runs str(s) to obtain the object’s string
representation for output.
 Here is the code for the __str__ method in the Student class:

Accessors and Mutators


 Methods that allow a user to observe but not change the state of an object are called
accessors.
 Methods that allow a user to modify an object’s state are called mutators.
 The Student class has just one mutator method. It allows the user to reset a test score at a
given position. The remaining methods are accessors.

Downloaded from Ktunotes.in


Structuring Classes with Inheritance and Polymorphism
 Data encapsulation: Restricting the manipulation of an object’s state by external users to
a set of method calls.
 Inheritance: Allowing a class to automatically reuse and extend the code of similar but
more general classes.
 Polymorphism: Allowing several different classes to use the same general method
names.
 Inheritance Hierarchies and Modeling: The path from a given class back up to the
topmost one goes through all of that given class’s ancestors. Each class below the
topmost one inherits attributes and behaviors from its ancestors and extends these with
additional attributes and behavior.

 An object-oriented software system models this pattern of inheritance and extension in


real-world systems by defining classes that extend other classes.
 In Python, all classes automatically extend the built-in object class, which is the most
general class possible.
 However, it is possible to extend any existing class using the syntax

 Thus, for example, PhysicalObject would extend object, LivingThing would extend
PhysicalObject, and so on.

Downloaded from Ktunotes.in


 The advantage of inheritance in a software system is that each new subclass acquires all
of the instance variables and methods of its ancestor classes for free, that allows the
programmer to avoid writing redundant code.
 Page no:332 for savings account class
 Page no: 334 for bank class
 Page no:350 for restricted savings account class
 Eg: Inheritance

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:

Downloaded from Ktunotes.in


y = Student("Mike", "Olsen")
y.printname()

 Add the __init__() function to the Student class:

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)

Downloaded from Ktunotes.in


 Add a property called graduationyear to the Student class:

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

x = Student("Mike", "Olsen", 2020)

 Add a method called welcome to the Student class:

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)

Downloaded from Ktunotes.in


 Polymorphic Methods: A subclass inherits data and methods from its parent class. A
subclass usually adds something extra, such as a new method or a data attribute. In some
cases, the two classes have the same interface, or set of methods available to external
users. In these cases, one or more methods in a subclass override the definitions of the
same methods in the superclass to provide specialized versions of the abstract behavior.
Like any object-oriented language, Python supports this capability with polymorphic
methods.

from math import pi

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

Downloaded from Ktunotes.in


def area(self):
return pi*self.radius**2

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).

Downloaded from Ktunotes.in


# Python program showing abstract base class work
from abc import ABC, abstractmethod
class Polygon(ABC):
# abstract method
def noofsides(self):
pass
class Triangle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
# overriding abstract method
def noofsides(self):

Downloaded from Ktunotes.in


print("I have 4 sides")
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
Output:
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides

Exceptions - Handle a single exception, handle multiple exceptions.


Exceptions:
 There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.
 Even if a statement or expression is syntactically correct, it may cause an error when an
attempt is made to execute it. Errors detected during execution are called exceptions.

>>> 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

Downloaded from Ktunotes.in


 The last line of the error message indicates what happened. Exceptions come in different
types, and the type is printed as part of the message: the types in the example are
ZeroDivisionError, NameError and TypeError.

Handling Exceptions/ Handle a single exception


 It is possible to write programs that handle selected exceptions.
 Python’s try-except statement is used for handling exceptions. This statement allows an
exception to be caught and the program to recover.
 The syntax of a simple try-except statement is the following:

 Example:

while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")

 The try statement works as follows.

 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.

Downloaded from Ktunotes.in


 If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer try statements; if no handler is found, it is
an unhandled exception and execution stops with a message as shown above.

Handle multiple exceptions

 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:

except (RuntimeError, TypeError, NameError):


... pass

 A class in an except clause is compatible with an exception if it is the same class or a


base class thereof (but not the other way around — an except clause listing a derived
class is not compatible with a base class).

Downloaded from Ktunotes.in

You might also like