Unit-3
Class Inheritance and polymorphism
Class:
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and
methods.
A Class is like an object constructor, or a "blueprint" for creating
objects.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to class.
Attributes are always public and can be accessed using dot (.)
operator. Eg.: [Link]
Class Definition Syntax:
class ClassName:
# Statement-1
....
# Statement-N
Defining a class
class Dog:
x=5
Class Objects
An Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values.
It’s not an idea anymore; it’s an actual dog, like a dog of breed pug
that’s seven years old. You can have many dogs to create many
different instances, but without the class as a guide, you would be lost,
not knowing what information is required.
An object consists of :
State: It is represented by attributes of an object. It also reflects
the properties of an object.
Behaviour: It is represented by methods of an object. It also
reflects the response of an object with other objects .
Identity: It gives a unique name to an object and enables one
object to interact with other objects.
class Dog:
# A simple class
# attribute
attr1 = "mamal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
[Link]()
Output:
mamal
I'm a mamal
I'm a dog
The self-parameter
The self-parameter refers to the current instance of the class and
accesses the class variables. We can use anything instead of self, but it
must be the first parameter of any function which belongs to the class .
Creating an instance of the class
A class needs to be instantiated if we want to use the class attributes in
another class or method. A class can be instantiated by calling the
class using the class name.
The syntax to create the instance of the class is given below.
1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee
defined in the above example.
Example
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%([Link],[Link]))
# Creating a emp instance of Employee class
emp = Employee()
[Link]()
Output:
ID: 10
Name: John
In the above code, we have created the Employee class which has two
attributes named id and name and assigned value to them. We can
observe we have passed the self as parameter in display function. It is
used to refer to the same class attribute.
We have created a new instance object named emp. By using it, we
can access the attributes of the class.
Delete the Object
We can delete the properties of the object or object itself by using the
del keyword. Consider the following example.
Example
class Employee:
id = 10
name = "John"
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
# Creating a emp instance of Employee class
emp = Employee()
# Deleting the property of object
del [Link]
# Deleting the object itself
del emp
[Link]()
Python Constructor
A constructor is a special type of method (function) which is used to
initialize the instance members of the class.
In C++ or Java, the constructor has the same name as its class, but it
treats constructor differently in Python. It is used to create an object.
Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this
class. Constructors also verify that there are enough resources for the
object to perform any start-up task.
Creating the constructor in python
In Python, the method the __init__() simulates the constructor of the
class. This method is called when the class is instantiated. It accepts
the self-keyword as a first argument which allows accessing the
attributes or method of the class.
We can pass any number of arguments at the time of creating the class
object, depending upon the __init__() definition. It is mostly used to
initialize the class attributes. Every class must have a constructor, even
if it simply relies on the default constructor.
Consider the following example to initialize the Employee class
attributes.
Example
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
[Link]()
# accessing display() method to print employee 2 information
[Link]()
Output:
ID: 101
Name: John
ID: 102
Name: David
Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to
manipulate the value or the constructor that has only self as an
argument. Consider the following example.
Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with
the self. Consider the following example.
Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()
Output:
This is parametrized constructor
Hello John
Python Default Constructor
When we do not include the constructor in the class or forget to
declare it, then that becomes the default constructor. It does not
perform any task but initializes the objects. Consider the following
example.
Example
class Student:
roll_num = 101
name = "Joseph"
def display(self):
print(self.roll_num,[Link])
st = Student()
[Link]()
Output:
101 Joseph
More than One Constructor in Single class
Let's have a look at another scenario, what happen if we declare the
two same constructors in the class.
Example
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")
st = Student()
Output:
The Second Constructor
In the above code, the object st called the second constructor whereas
both have the same configuration. The first method is not accessible by
the st object. Internally, the object of the class will always call the last
constructor if the class has multiple constructors.
Python built-in class functions(*)
The built-in functions defined in the class are described in the following table.
SN Function Description
1 getattr(obj,name,default) It is used to access the attribute of the
object.
2 setattr(obj, name,value) It is used to set a particular value to
the specific attribute of an object.
3 delattr(obj, name) It is used to delete a specific attribute.
4 hasattr(obj, name) It returns true if the object contains
some specific attribute.
class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age
# creates the object of the class Student
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print([Link])
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
Along with the other attributes, a Python class also contains some built-in class
attributes which provide information about the class.
The built-in class attributes are given in the below table.
SN Attribute Description
1 __dict__ It provides the dictionary containing the information
about the class namespace.
2 __doc__ It contains a string which has the class
documentation
3 __name__ It is used to access the class name.
4 __module__ It is used to access the module in which, this class is
defined.
5 __bases__ It contains a tuple including all base classes.
Example
class Student:
def __init__(self,name,id,age):
[Link] = name;
[Link] = id;
[Link] = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%([Link],[Link]))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Types of Methods in Python
There are three types of methods in Python:
1. Instance Methods.
2. Class Methods
3. Static Methods
1. Instance Method
This is a very basic and easy method that we use regularly when we
create classes in python. If we want to print an instance variable or
instance method we must create an object of that required class.
If we are using self as a function parameter or in front of a variable, that is
nothing but the calling instance itself.
As we are working with instance variables we use self keyword.
Note: Instance variables are used with instance methods.
Look at the code below
# Instance Method Example in Python
class Student:
def __init__(self, a, b):
self.a = a
self.b = b
def avg(self):
return (self.a + self.b) / 2
s1 = Student(10, 20)
print( [Link]() )
Output:
15.0
2. Class Method
classsmethod() function returns a class method as output for the given
function.
Here is the syntax for it:
classmethod(function)
The classmethod() method takes only a function as an input parameter
and converts that into a class method.
There are two ways to create class methods in python:
1. Using classmethod(function)
2. Using @classmethod annotation
A class method can be called either using the class (such as C.f()) or
using an instance (such as C().f()). The instance is ignored except for its
class. If a class method is called from a derived class, the derived class
object is passed as the implied first argument.
As we are working with ClassMethod we use the cls keyword. Class
variables are used with class methods.
Look at the code below.
# Class Method Implementation in python
class Student:
name = 'Student'
def __init__(self, a, b):
self.a = a
self.b = b
@classmethod
def info(cls):
return [Link]
print([Link]())
Output:
Student
In the above example, name is a class variable. If we want to create a class
method we must use @classmethod decorator and cls as a parameter for
that function.
3. Static Method
A static method can be called without an object for that class, using the
class name directly. If you want to do something extra with a class we use
static methods.
For example, If you want to print factorial of a number then we don't need
to use class variables or instance variables to print the factorial of a
number. We just simply pass a number to the static method that we have
created and it returns the factorial.
Look at the below code
# Static Method Implementation in python
class Student:
name = 'Student'
def __init__(self, a, b):
self.a = a
self.b = b
@staticmethod
def info():
return "This is a student class"
print([Link]())
Output
This a student class
Accessing attributes and methods of one class in another class
Accessing attributes and methods of one class in another class is done by
passing the object of one class to another.
Explained with the example given below :
# Python code for Accessing attributes and methods
# of one class in another class
class ClassA():
def __init__(self):
self.var1 = 1
self.var2 = 2
def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1
class ClassB(ClassA):
def __init__(self, class_a):
self.var1 = class_a.var1
self.var2 = class_a.var2
object1 = ClassA()
# updates the value of var1
summ = [Link]()
# return the value of var1
print summ
# passes object of classA
object2 = ClassB(object1)
# return the values carried by var1,var2
print object2.var1
print object2.var2
Output :
3
3
2
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide
its specific implementation to the functions of the parent class. In this section of
the tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in
the bracket after the derived class name. Consider the following syntax to inherit
a base class into the derived class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.
Syntax
class deriveclass(<base class 1>, <base class 2>,
..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages.
Multi-level inheritance is archived when a derived class inherits another derived
class. There is no limit on the number of levels up to which, the multi-level
inheritance is archived in python.
The syntax of multi-level inheritance is given below.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
[Link]()
[Link]()
[Link]()
Output:
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child
class.
The syntax to perform multiple inheritance is given below.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
class Derived(Base1, Base2, ...... BaseN):
<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
Output:
30
200
0.5
Method resolution order
MRO stands for Method Resolution Order. It is the order in which Python
looks for a method in a hierarchy of classes. MRO follows a specific
sequence to determine which method to invoke when it encounters
multiple classes with the same method name
For Example :
# Python program showing
# how MRO works
class A:
def rk(self):
print("In class A")
class B(A):
def rk(self):
print("In class B")
r = B()
[Link]()
Python Constructors
A constructor is a class function that instantiates an object to
predefined values.
It begins with a double underscore (_). It __init__() method
In below example we are taking name of the user using constructor.
class User:
name = ""
def __init__(self, name):
[Link] = name
def sayHello(self):
print("Welcome to Guru99, " + [Link])
User1 = User("Alex")
[Link]()
Output will be:
Welcome to Guru99, Alex
What is Polymorphism?
Polymorphism is taken from the Greek words Poly (many) and morphism
(forms). It means that the same function name can be used for different
types. This makes programming more intuitive and easier.
In Python, we have different ways to define polymorphism. So let’s move
ahead and see how polymorphism works in Python.
class Tomato():
def type(self):
print("Vegetable")
def color(self):
print("Red")
class Apple():
def type(self):
print("Fruit")
def color(self):
print("Red")
def func(obj):
[Link]()
[Link]()
obj_tomato = Tomato()
obj_apple = Apple()
func(obj_tomato)
func(obj_apple.
Polymorphism with Inheritance:
In Python, Polymorphism lets us define methods in the child class that have
the same name as the methods in the parent class. In inheritance, the child
class inherits the methods from the parent class. However, it is possible to
modify a method in a child class that it has inherited from the parent class.
This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class. In such cases, we re-
implement the method in the child class. This process of re-implementing a
method in the child class is known as Method Overriding.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
developed country.
What is Exception? How to handle Exception in python
explain with example?
An exception can be defined as an abnormal condition in a
program resulting in the disruption in the flow of the program.
Whenever an exception occurs, the program halts the execution,
and thus the further code is not executed. Therefore, an
exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that
the other part of the code can be executed without any
disruption.
However, if we do not handle the exception, the interpreter
doesn't execute all the code that exists after that.
Common Exceptions
A list of common exceptions that can be thrown from a normal
python program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or
global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
Exception handling in python
If the python program contains suspicious code that may throw
the exception, we must place that code in the try block.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:")) c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
Enter a:10 Enter b:2 a/b = 5
Hi I am else block
Write a short note on Types of Exception.
There are several exceptions available as part of python
language that are called built-in exceptions.
In the same way, the programmer can also create his own
exceptions called user defined exceptions.
[Link]. Exception Name & Description
1 Exception
Base class for all exceptions
2 ArithmeticError
Base class for all errors that occur for numeric calculation.
3 OverflowError
Raised when a calculation exceeds maximum limit for a
numeric type.
4 FloatingPointError
Raised when a floating point calculation fails.
5 ZeroDivisionError
Raised when division or modulo by zero takes place for all
numeric types.
6 EOFError
Raised when there is no input from either the raw_input() or
input() function and the end of file is reached.
7 ImportError
Raised when an import statement fails.
8 KeyboardInterrupt
Raised when the user interrupts program execution, usually
by pressing Ctrl+c.
9 IndexError
Raised when an index is not found in a sequence.
10 NameError
Raised when an identifier is not found in the local or global
namespace.
11 IOError
Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
12 SyntaxError
Raised when there is an error in Python syntax.
13 IndentationError
Raised when indentation is not specified properly.
14 SystemError
Raised when the interpreter finds an internal problem, but when
this error is encountered the Python interpreter does not exit.
15 ValueError
Raised when the built-in function for a data type has the valid type
of arguments, but the arguments have invalid values specified.
16 RuntimeError
Raised when a generated error does not fall into any category.