Chapter 9-1
Chapter 9-1
Contents
1. Classes in Python .................................................................................................................................. 1
2. Principles of Object Orientation ........................................................................................................... 1
3. Creating Classes .................................................................................................................................... 2
4. Instance Methods .................................................................................................................................. 2
5. File Organization .................................................................................................................................. 9
6. Special Methods .................................................................................................................................... 9
7. Class Variables...................................................................................................................................... 9
8. Inheritance........................................................................................................................................... 11
9. Polymorphism ..................................................................................................................................... 20
1. Classes in Python
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a
means of bundling data and functionality together. Creating a new class creates a new type of
object, allowing new instances of that type to be made. Each class instance can have attributes
attached to it for maintaining its state. Class instances can also have methods (defined by their
class) for modifying their state.
Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.
Defining a class
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass
In the above example, the class keyword indicates that you are creating a class followed by the
name of the class (Dog in this case).
4. Instance Methods
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
who’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 the attributes of an object. It also reflects the properties of an object.
Behaviour: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Declaring an object
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
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()
Output
mammal
I'm a mammal
I'm a dog
In the above example, an object is created which is basically a dog named Rodger. This class only
has two class attributes that tell us that Rodger is a dog and a mammal.
The self
Class methods must have an extra first parameter in the method definition. We do not give a value
for this parameter when we call the method, Python provides it. If we have a method that takes no
arguments, we still have one argument. This is similar to this pointer in C++ and this reference in
Java. When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is
about.
__init__ method
The __init__ method is similar to constructors in C++ and Java. Constructors are used to initialize
the object’s state. Like methods, a constructor also contains a collection of statements(i.e.
instructions) that are executed at the time of Object creation. It runs as soon as an object of a class
is instantiated. The method is useful to do any initialization you want to do with your object.
Python3
# Sample class with init method
class Person:
p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil
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.
• Parameterized Constructor
• 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):
self.id = id
self.name = name
def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
# accessing display() method to print employee 1 information
emp1.display()
# accessing display() method to print employee 2 information
emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
Instance Method
Instance attributes are those attributes that are not shared by objects. Every object has its own
copy of the instance attribute.
For example, consider a class shapes that have many objects like circle, square, triangle, etc.
having its own attributes and methods. An instance attribute refers to the properties of that
particular object like edge of the triangle being 3, while the edge of the square can be 4.
An instance method can access and even modify the value of attributes of an instance. It has one
default parameter:-
self – It is a keyword which points to the current passed instance. But it need not be passed every
time while calling an instance method.
Example:
class shape:
# Calling Constructor
def __init__(self, edge, color):
self.edge = edge
self.color = color
# Instance Method
def finEdges(self):
return self.edge
# Instance Method
def modifyEdges(self, newedge):
self.edge = newedge
# Driver Code
circle = shape(0, 'red')
square = shape(4, 'blue')
Output
No. of edges for circle: 0
No. of edges for square: 6
5. File Organization
6. Special Methods
7. Class Variables
Instance variables are for data, unique to each instance and class variables are for attributes and
methods shared by all instances of the class. Instance variables are variables whose value is
assigned inside a constructor or method with self whereas class variables are variables whose value
is assigned in the class.
Defining instance variables using a constructor.
class Dog:
# Class Variable
animal = 'dog'
# The init method or constructor
def __init__(self, breed, color):
# Instance Variable
self.breed = breed
self.color = color
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
Output
Rodger details:
Rodger is a dog
Breed: Pug
Color: brown
Buzo details:
Buzo is a dog
Breed: Bulldog
Color: black
class Dog:
# Class Variable
animal = 'dog'
# Instance Variable
self.breed = breed
# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())
Output
brown
8. Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class. The
class that derives properties is called the derived class or child class and the class from which the
properties are being derived is called the base class or parent class. The benefits of inheritance are:
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and again. Also,
it allows us to add more features to a class without modifying it.
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.
Types of Inheritance –
Single Inheritance:
Single-level inheritance enables a derived class to inherit characteristics from a single-parent
class.
Multilevel Inheritance:
Multi-level inheritance enables a derived class to inherit properties from an immediate parent
class which in turn inherits properties from his parent class.
Hierarchical Inheritance:
Hierarchical level inheritance enables more than one derived class to inherit properties from a
parent class.
Multiple Inheritance:
Multiple level inheritance enables one derived class to inherit properties from more than one
base class.
Example: Inheritance in Python
# parent class
class Person(object):
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern
In the above program, two classes have been created i.e. Person (parent class) and Employee (Child
Class). The Employee class inherits from the Person class. We can use the methods of the person
class through employee class as seen in the display function in the above code. A child class can
also modify the behavior of the parent class as seen through the details() method.
One of the core concepts in object-oriented programming (OOP) languages is inheritance. It is a
mechanism that allows you to create a hierarchy of classes that share a set of properties and methods by
deriving a class from another class. Inheritance is the capability of one class to derive or inherit the
properties from another class.
Benefits of inheritance are:
• It represents real-world relationships well.
• It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
• 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.
• Less development and maintenance expenses result from an inheritance.
Python Inheritance Syntax
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Creating a Parent Class
Creating a Person class with Display methods.
class Person(object):
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id
# Driver code
emp = Person("Satyam", 102) # An Object of Person
emp.Display()
Output:
Satyam 102
Creating a Child Class
Here Emp is another class which is going to inherit the properties of the Person class(base class).
Python3
class Emp(Person):
def Print(self):
print("Emp class called")
Output:
Mayank 103
Emp class called
Example of Inheritance in Python
# A Python program to demonstrate inheritance
class Person(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())
Output:
Geek1 False
Geek2 True
# parent class
class Person(object):
def display(self):
print(self.name)
print(self.idnumber)
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
Output:
Rahul
886012
‘a’ is the instance created for the class Person. It invokes the __init__() of the referred class. You can see
‘object’ written in the declaration of the class Person. In Python, every class inherits from a built-in basic
class called ‘object’. The constructor i.e. the ‘__init__’ function of a class is invoked when we create an
object variable or an instance of the class.
The variables defined within __init__() are called the instance variables or objects. Hence, ‘name’ and
‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are the objects of the class
Employee. Since the class Employee inherits from class Person, ‘name’ and ‘idnumber’ are also the
objects of class Employee.
Python program to demonstrate error if we forget to invoke __init__() of the parent
If you forget to invoke the __init__() of the parent class then its instance variables would not be available
to the child class.
The following code produces an error for the same reason.
class A:
def __init__(self, n='Rahul'):
self.name = n
class B(A):
def __init__(self, roll):
self.roll = roll
object = B(23)
print(object.name)
Output :
Traceback (most recent call last):
File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in
print (object.name)
AttributeError: 'B' object has no attribute 'name'
Different types of Inheritance:
Single inheritance: When a child class inherits from only one parent class, it is called single
inheritance. We saw an example above.
Multiple inheritances: When a child class inherits from multiple parent classes, it is called multiple
inheritances.
Unlike java, python shows multiple inheritances.
Python3
# Python example to show the working of multiple
# inheritance
class Base1(object):
def __init__(self):
self.str1 = "Geek1"
print("Base1")
class Base2(object):
def __init__(self):
self.str2 = "Geek2"
print("Base2")
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
Output:
Base1
Base2
Derived
Geek1 Geek2
Multilevel inheritance: When we have a child and grandchild relationship.
Python3
# A Python program to demonstrate inheritance
class Base(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
# To get name
def getAge(self):
return self.age
class GrandChild(Child):
# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address
# To get address
def getAddress(self):
return self.address
# Driver code
g = GrandChild("Geek1", 23, "Noida")
print(g.getName(), g.getAge(), g.getAddress())
Output:
Geek1 23 Noida
Hierarchical inheritance More than one derived class are created from a single base.
Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend
of more than one type of inheritance.
For more details please read this article: Types of inheritance in Python
Private members of the parent class
We don’t always want the instance variables of the parent class to be inherited by the child class i.e. we
can make some of the instance variables of the parent class private, which won’t be available to the child
class.
We can make an instance variable private by adding double underscores before its name. For example,
Python3
# Python program to demonstrate private members
# of the parent class
class C(object):
def __init__(self):
self.c = 21
class D(C):
def __init__(self):
self.e = 84
C.__init__(self)
object1 = D()
Output :
File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py", line 16, in
print (object1.d)
AttributeError: type object 'D' has no attribute 'd'
Since ‘d’ is made private by those underscores, it is not available to the child class ‘D’ and hence the
error.
9. Polymorphism
The literal meaning of polymorphism is the condition of occurrence in different forms.
Polymorphism is a very important concept in programming. It refers to the use of a single type
entity (method, operator or object) to represent different types in different scenarios.
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Bark")
Here, we have created two classes Cat and Dog. They share a similar structure and have the same
method names info() and make_sound().
However, notice that we have not created a common superclass or linked the classes together in
any way. Even then, we can pack these two different objects into a tuple and iterate through it
using a common animal variable. It is possible due to polymorphism.
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
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())
Run Code
Output
Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985
Here, we can see that the methods such as __str__(), which have not been overridden in the child
classes, are used from the parent class.
Due to polymorphism, the Python interpreter automatically recognizes that the fact() method for
object a(Square class) is overridden. So, it uses the one defined in the child class.
On the other hand, since the fact() method for object b isn't overridden, it is used from the
Parent Shape class.
Polymorphism in
parent and child classes in Python
Note: Method Overloading, a way to create multiple methods with the same name but different
arguments, is not possible in Python.