Professional Documents
Culture Documents
Unit 4
Unit 4
p1=Person(“John”, 30)
print(p1.name)
print(p2.age)
Python- Objects and Classes
• Python allows us to define classes to create objects.
• A class is a collection of instance variables and its related
methods that define an object type.
• A class is a blueprint or a template that defines a set of
attributes that characterize an object.
• Class variable − A variable that is shared by all instances of a
class. Class variables are defined within a class but outside any
of the class's methods. Class variables are not used as
frequently as instance variables are.
• Instance variable − A variable that is defined inside a method
and belongs only to the current instance of a class.
• Method − A special kind of function that is defined in a class
definition.
• Object − A unique instance of a class. An object comprises
both data members (class variables and instance variables)
and methods.
• A program to create a class called Employee.
Object Lifecycle
• The lifecycle of an object starts from its creation or construction
and ends with its destruction.
• The object creation is done with the help of a special method
called constructor and destruction takes place with the help of a
destructor method.
• A constructor is a special type of method which is used to
initialize the instance members of the class.
• Syntax of constructor declaration:
def __init__(self):
# body of the constructor
• Destructors are called when an object gets destroyed. Python has a
garbage collector that handles memory management automatically.
• The __del__( ) method is known as a destructor method in Python.
It is called when all references to the object have been deleted i.e.,
when an object is garbage collected.
Syntax of destructor declaration:
def __del__(self):
# body of destructor
Applications
• Classes and objects are frequently used in real world applications like
Web Development, Game Development, Scientific and Numeric
Applications, Artificial Intelligence and Machine Learning, Software
Development, Enterprise-level/Business Applications, Education
programs and training courses, Language Development etc.
Examples
1. Develop a Python program to create a class Student with instance variables
usn, name and marks. Create two objects and display the details of the students
who has got the highest mark.
2. Develop a Python program to create a class Actor with instance variables
actorid, actorname, no_movies and earnings. Create three actors and display
the details of the actor whose average earning is the minimum.
3. Develop a Python program which creates the class Circle that has member
radius. Include methods to do the following.
a. Accept the radius from the user
b. Find the area of the circle
c. Find the perimeter of the circle
d. Display all the details
4. Develop a Python program to create a class Employee with members
empid, empname, empnohrs, empbasic, emphra(%),
empda(%),empit(%), empgross. Include methods to do the following:
a. Accept all values from the user. Note House rent allowance,
dearness allowance and income tax are given in %
b. Calculate the gross salary based on the formula
empgross= empbasic + empbasic*emphra + empbasic*empda -
empbasic*empit
c. Consider the overtime amount to be Rs.100 per hour. If empnohrs
>200, for every hour the employee is to be given additional payment.
Calculate the additional payment and update the gross. If
empnohrs<200, reduce Rs.100 per hour and update the gross.
5. A Multispeciality hospital wants to calculate the bill amount to be
paid by patients visiting the hospital. Bill amount includes consultation
fees and lab charges. Write a Python program to implement the class
with members- bill_id, patient_name and bill_amount. Include
methods of form:
a. __init__(bill_id, patient_name)
b. Calc_billamt (consultation_fees, labcharges)
c. Display the details – bill_id, patient_name and bill_amount
A discount of 10% can be given if the lab charges exceed Rs.25000. 5%
Discount can be given if lab charges exceeds Rs.10000/-
Inheritance
• One of the core concepts in object-oriented programming
(OOP) languages is inheritance.
• It is a mechanism that allows us to create a hierarchy of classes
that share a set of properties and methods. When one class
inherits from another, it automatically takes on all the
attributes and methods of the first class but is also free to
define new attributes and methods of its own.
• The original class is called the parent class or base class or
super class, and the new class is the child class or derived class
or sub class.
Advantages of Inheritance
• It represents real-world relationships well.
• It provides the reusability of a code. Repeating the same
code again in another class is avoided as well, more features
can be added without modifying existing ones.
• It is transitive in nature, which means that if class B inherits
from another class A, then all the subclasses of B would
automatically inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Development and maintenance expenses are comparatively
reduced.
Python Inheritance Syntax
class BaseClass:
{Body}
class DerivedClass (BaseClass):
{Body}
# Derived class
class Car(Vehicle):
def car_info(self):
print('Inside Car class') Inside Vehicle class
Inside Car class
# Create object of Car
car = Car()
C1 = Complex(3, 2);
print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary))
C2 = Complex(9, 5);
print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary))
C3 = C1 + C2;
print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary))
Example
• Develop a Python program to create a class Time with data
members – hours and minutes. Include the following methods:
• A parameterized constructor to set values to the hours and
minutes,
• A method ‘accept’ to accept the values for the members from the
user.
• Overload the + operator to add two given times. Ex. If Time1 has
hours=11 minutes=50 and Time2 has hours =4 minutes =40, then
Time3 should be hours=16 minutes=30
• A method to display the all the time objects.
• Create two objects of class Time and assign the sum of these two
objects to a third object.
Exceptions
• Errors detected during execution of programs are called
exceptions. Even if a statement or expression is syntactically
correct, it may cause an error when an attempt is made to
execute it. An exception is an event raised that disrupts the
normal flow of the program's instructions and is seen
everywhere in Python.
• Situations where exceptions can occur:
• Division by 0
• Opening a file
• Index out of bound ---- etc.
• Example --
Built-in Exception types in Python
• Python has a number of built-in exceptions that are derived from the
Exception class.
• Some of them are listed below:
1. SyntaxError: This exception is raised when a syntax error is
encountered in the code, such as a missing colon, wrong keyword etc.
2. TypeError: This exception is raised when an operation or function is
applied to a wrong type, such as dividing 2 strings.
3. ZeroDivisionError: This exception is raised when we try to divide a
number by 0.
4. KeyError: This exception is raised when a key is not found in the
dictionary.
5. NameError: When a function is not found in the current scope.
6. AttributeError: When an attribute or method is not found on an
object.
7. ImportError: This exception occurs when an import statement
fails to find or load the module.
8. IndexError: When the index is out of range for the collection
types.
Exception Handling
• Exception handling allows us to separate error-handling code
from normal code.
• The main advantage of exception handling is that it allows the
smooth ending of the programs when exceptions occur, instead
of abrupt ending.
• Exceptions must be class objects
• For class exception, we can use a try statement with an except
clause which mentions a particular class.
Python Exception Handling Mechanism
1. Exception handling is managed by the following 4 keywords:
1. try 2. except 3. finally 4. raise
• Format for handling exception:
try:
# Some Code....
except:
# executes when an exception occurs
# Handling of exception (if required)
else:
# executes if no exception
finally:
# Some code .....(always executed)
Examples
• 1. Input a number from the keyboard and raise an exception
if the input is not a number.
• 2. Write a python program that accepts two numbers from
the user and performs their division. It should raise an
exception for division by zero error, value error and have a
finally block.
• Write a program to demonstrate the use of try, except and
else in python exception handling.
User Defined Exceptions
• When programs for real life applications in Python are written,
there are many constraints on the values which the variables can
take in the program. For example, age cannot have a negative
value. When a person inputs a negative value for age, the program
should show an error message.
• These type of errors cannot be caught by built-in exception types.
Hence, we need to define our own exception classes that derive
from the Exception class.
• The keyword raise is used to raise a specific exception.
Example: Exception that handles negative
numbers in squareroot operation
Examples
• Write a python program to check the validity of the age. Raise an
exception if the entered age is less than 0.
• Write a Python program that demonstrates handling of exceptions
in inheritance tree. Create a base class called “Father” and a
derived class called “Son” which extends the base class. In Father
class, implement a constructor which takes the age and throws the
exception WrongAge( ) when the input age<0. In Son class,
implement a constructor that checks both father and son’s age and
throws an exception if son’s age is greater than or equal to father’s
age.