Unit 4 Python L
Unit 4 Python L
OOPs
Python Class
A class is a collection of objects. A class contains the blueprints or the prototype
from which the objects are being created. It is a logical entity that contains some
attributes and methods.
To understand the need for creating a class let’s consider an example, let’s say you
wanted to track the number of dogs that may have different attributes like breed, and
age. If a list is used, the first element could be the dog’s breed while the second
element could represent its age. Let’s suppose there are 100 different dogs, then how
would you know which element is supposed to be which? What if you wanted to add
other properties to these dogs? This lacks organization and it’s the exact need for
classes.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator.
Eg.: Myclass.Myattribute
Class Definition Syntax:
class ClassName:
# Statement-1
.
.
.
# Statement-N
In the above example, we have created a class named Dog using the class keyword.
Python
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass
Python Objects
The object is an entity that has a state and behavior associated with it. It may be any
real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings,
floating-point numbers, even arrays, and dictionaries, are all objects. More
specifically, any single integer or any single string is an object. The number 12 is an
object, the string “Hello, world” is an object, a list is an object that can hold other
objects, and so on. You’ve been using objects all along and may not even realize it.
An object consists of:
State: It is represented by the attributes of an object. It also reflects the
properties of an object.
Behavior: 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.
To understand the state, behavior, and identity let us take the example of the class
dog (explained above).
The identity can be considered as the name of the dog.
State or Attributes can be considered as the breed, age, or color of the dog.
The behavior can be considered as to whether the dog is eating or
sleeping.
Creating an Object
This will create an object named obj of the class Dog defined above. Before diving
deep into objects and classes let us understand some basic keywords that will we
used while working with objects and classes.
Python3
obj = Dog()
Python3
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
print("Rodger is a {}".format(Rodger.__class__.attr1))
Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Python3
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
self.name = name
def speak(self):
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
Rodger.speak()
Tommy.speak()
Output
My name is Rodger
My name is Tommy
Note: For more information, refer to Python Classes and Objects
Python 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.
Inheritance in Python
In the above article, we have created two classes 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 the 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.
Python3
# Python code to demonstrate how parent constructors
# are called.
# parent class
class Person(object):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
self.salary = salary
self.post = post
def details(self):
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
# its instance
a.display()
a.details()
Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern
Note: For more information, refer to our Inheritance in Python tutorial.
Python Polymorphism
Polymorphism simply means having many forms. For example, we need to
determine if the given species of birds fly or not, using polymorphism we can do this
using a single function.
Polymorphism in Python
This code demonstrates the concept of inheritance and method overriding in Python
classes. It shows how subclasses can override methods defined in their parent class
to provide specific behavior while still inheriting other methods from the parent
class.
Python3
class Bird:
def intro(self):
def flight(self):
class sparrow(Bird):
def flight(self):
class ostrich(Bird):
def flight(self):
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()
Output
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.
Note: For more information, refer to our Polymorphism in Python Tutorial.
Python Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming
(OOP). It describes the idea of wrapping data and the methods that work on data
within one unit. This puts restrictions on accessing variables and methods directly
and can prevent the accidental modification of data. To prevent accidental change,
an object’s variable can only be changed by an object’s method. Those types of
variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Encapsulation in Python
In the above example, we have created the c variable as the private attribute. We
cannot even access this attribute directly and can’t even change its value.
Python3
# Python program to
class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"
class Derived(Base):
def __init__(self):
# Calling constructor of
# Base class
Base.__init__(self)
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
# raise an AttributeError
Output
GeeksforGeeks
Note: for more information, refer to our Encapsulation in Python Tutorial.
Data Abstraction
It hides unnecessary code details from the user. Also, when we do not want to give
out sensitive parts of our code implementation and this is where data abstraction
came.
Data Abstraction in Python can be achieved by creating abstract classes.
Inheritance in Python
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:
Inheritance allows you to inherit the properties of a class, i.e., base class to another,
i.e., derived class. The benefits of Inheritance in Python are as follows:
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
The syntax of simple inheritance in Python is as follows:
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
A parent class is a class whose properties are inherited by the child class. Let’s
create a parent class called Person which has a Display method to display the
person’s information.
Python3
# A Python program to demonstrate inheritance
class Person(object):
# Constructor
self.name = name
self.id = id
def Display(self):
print(self.name, self.id)
# Driver code
emp.Display()
Output:
Satyam 102
A child class is a class that drives the properties from its parent class. Here Emp is
another class that is going to inherit the properties of the Person class(base class).
Python3
class Emp(Person):
def Print(self):
Emp_details.Display()
Emp_details.Print()
Output:
Mayank 103
Emp class called
Example of Inheritance in Python
Let us see an example of simple Python inheritance in which a child class is
inheriting the properties of its parent class. In this example, ‘Person’ is the parent
class, and ‘Employee’ is its child class.
Python3
# A Python program to demonstrate inheritance
class Person(object):
# Constructor
self.name = name
# To get name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
# Here we return true
def isEmployee(self):
return True
# Driver code
print(emp.getName(), emp.isEmployee())
print(emp.getName(), emp.isEmployee())
Output:
Geek1 False
Geek2 True
# single inheritance
# Base class
class Parent:
def func1(self):
# Derived class
class Child(Parent):
def func2(self):
object = Child()
object.func1()
object.func2()
Output:
This function is in parent class.
This function is in child class.
Multiple Inheritance:
When a class can be derived from more than one base class this type of inheritance
is called multiple inheritances. In multiple inheritances, all the features of the base
classes are inherited into the derived class.
Example:
Python3
# Python program to demonstrate
# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
def parents(self):
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Output:
Father : RAM
Mother : SITA
Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a
child and a grandfather.
Example:
Python3
# Python program to demonstrate
# multilevel inheritance
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
self.fathername = fathername
Grandfather.__init__(self, grandfathername)
# Derived class
class Son(Father):
self.sonname = sonname
def print_name(self):
print(s1.grandfathername)
s1.print_name()
Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance:
When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a parent
(base) class and two child (derived) classes.
Example:
Python3
# Python program to demonstrate
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
# Derived class1
class Child1(Parent):
def func2(self):
# Derivied class2
class Child2(Parent):
def func3(self):
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
Example:
Python3
# Python program to demonstrate
# hybrid inheritance
class School:
def func1(self):
class Student1(School):
def func2(self):
def func3(self):
def func4(self):
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.
Python was designed with OOP approach and it offers the following
advantages:
We can also create multiple objects from a single class. For example,
# define a class
class Employee:
# define an attribute
employee_id = 0
Output
# create a class
class Room:
length = 0.0
breadth = 0.0
Output
Method: calculate_area()
Here, we have created an object named study_room from the Room class. We
then used the object to assign values to attributes: length and breadth .
Notice that we have also used the object to call the method inside the
class,
study_room.calculate_area()
Here, we have used the . notation to call the method. Finally, the statement
inside the method is executed.
Python Constructors
class Bike:
name = ""
...
# create object
bike1 = Bike()
However, we can also initialize values using the constructors. For example,
class Bike:
# constructor function
def __init__(self, name = ""):
self.name = name
bike1 = Bike()
Syntax
1. class ClassName:
2. #statement_suite
In Python, we must notice that each class is associated with a documentation string
which can be accessed by using <class-name>.__doc__. A class contains a statement
suite including fields, constructor, function, etc. definition.
Example:
Code:
1. class Person:
2. def __init__(self, name, age):
3. # This is the constructor method that is called when creating a new Perso
n object
4. # It takes two parameters, name and age, and initializes them as attributes of the
object
5. self.name = name
6. self.age = age
7. def greet(self):
8. # This is a method of the Person class that prints a greeting message
9. print("Hello, my name is " + self.name)
Name and age are the two properties of the Person class. Additionally, it has a
function called greet that prints a greeting.
Objects in Python:
An object is a particular instance of a class with unique characteristics and functions.
After a class has been established, you may make objects based on it. By using the
class constructor, you may create an object of a class in Python. The object's
attributes are initialised in the constructor, which is a special procedure with the
name __init__.
Syntax:
Example:
Code:
1. class Person:
2. def __init__(self, name, age):
3. self.name = name
4. self.age = age
5. def greet(self):
6. print("Hello, my name is " + self.name)
7.
8. # Create a new instance of the Person class and assign it to the variable person1
9. person1 = Person("Ayan", 25)
10. person1.greet()
Output:
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.
_ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is
called. Although it is used to set the object's attributes, it is often referred to as a
constructor.
The self-argument is the only one required by the __init__ method. This argument
refers to the newly generated instance of the class. To initialise the values of each
attribute associated with the objects, you can declare extra arguments in the __init__
method.
Class and Instance Variables
All instances of a class exchange class variables. They function independently of any
class methods and may be accessed through the use of the class name. Here's an
illustration:
Code:
1. class Person:
2. count = 0 # This is a class variable
3.
4. def __init__(self, name, age):
5. self.name = name # This is an instance variable
6. self.age = age
7. Person.count += 1 # Accessing the class variable using the name of the
class
8. person1 = Person("Ayan", 25)
9. person2 = Person("Bobby", 30)
10. print(Person.count)
Output:
Whereas, instance variables are specific to each instance of a class. They are specified
using the self-argument in the __init__ method. Here's an illustration:
Code:
1. class Person:
2. def __init__(self, name, age):
3. self.name = name # This is an instance variable
4. self.age = age
5. person1 = Person("Ayan", 25)
6. person2 = Person("Bobby", 30)
7. print(person1.name)
8. print(person2.age)
Output:
Ayan
30
Class variables are created separately from any class methods and are shared by all
class copies. Every instance of a class has its own instance variables, which are
specified in the __init__ method utilising the self-argument.
class Geeksforgeeks :
gfg = 10
First of all, we have to understand the __init__() built-in method for understanding
the meaning of classes. Whenever the class is being initiated, a method namely
__init__() is always executed. An __init__() method is used to assign the values to
object properties or to perform the other method that is required to complete when
the object is created.
Example: class with __init__() method
Python3
class Geeksforgeeks:
# constructor method
def __init__(self):
# object attributes
def show(self):
print("Course:", self.course)
print("Duration:", self.duration)
# create Geeksforgeeks
# class object
outer = Geeksforgeeks()
# method calling
outer.show()
Output:
Course : Campus Preparation
Duration : As per your schedule
Inner Class in Python
A class defined in another class is known as an inner class or nested class. If an
object is created using child class means inner class then the object can also be used
by parent class or root class. A parent class can have one or more inner classes but
generally inner classes are avoided.
We can make our code even more object-oriented by using an inner class. A single
object of the class can hold multiple sub-objects. We can use multiple sub-objects to
give a good structure to our program.
Example:
First, we create a class and then the constructor of the class.
After creating a class, we will create another class within that class, the
class inside another class will be called an inner class.
Python3
class Color:
# constructor method
def __init__(self):
# object attributes
self.name = 'Green'
self.lg = self.Lightgreen()
def show(self):
class Lightgreen:
def __init__(self):
self.code = '024avc'
def display(self):
outer = Color()
# method calling
outer.show()
# create a Lightgreen
g = outer.lg
g.display()
Output:
Name: Green
Name: Light Green
Code: 024avc
Why inner class?
For the grouping of two or more classes. Suppose we have two classes remote and
battery. Every remote needs a battery but a battery without a remote won’t be used.
So, we make the Battery an inner class to the Remote. It helps us to save code. With
the help of the inner class or nested class, we can hide the inner class from the
outside world. Hence, Hiding the code is another good feature of the inner class. By
using the inner class, we can easily understand the classes because the classes are
closely related. We do not need to search for classes in the whole code, they all are
almost together. Though inner or nested classes are not used widely in Python it will
be a better feature to implement code because it is straightforward to organize when
we use inner class or nested class.
Syntax:
# create NameOfOuterClass class
class NameOfOuterClass:
The class contains one or more inner classes known as multiple inner classes. We
can have multiple inner class in a class, it is easy to implement multiple inner
classes.
Example: Multiple inner class
Python3
class Doctors:
def __init__(self):
self.name = 'Doctor'
self.den = self.Dentist()
self.car = self.Cardiologist()
def show(self):
print('In outer class')
print('Name:', self.name)
class Dentist:
def __init__(self):
self.degree = 'BDS'
def display(self):
print("Name:", self.name)
print("Degree:", self.degree)
class Cardiologist:
def __init__(self):
self.degree = 'DM'
def display(self):
print("Name:", self.name)
print("Degree:", self.degree)
# create a object
# of outer class
outer = Doctors()
outer.show()
# create a object
# of 1st inner class
d1 = outer.den
# create a object
d2 = outer.car
print()
d1.display()
print()
d2.display()
Output
In outer class
Name: Doctor
The class contains an inner class and that inner class again contains another inner
class, this hierarchy is known as the multilevel inner class.
Example: Multilevel inner class
Python3
class Geeksforgeeks:
def __init__(self):
def show(self):
class Inner:
def __init__(self):
self.innerclassofinner = self.Innerclassofinner()
def show(self):
class Innerclassofinner:
def show(self):
outer = Geeksforgeeks()
outer.show()
print()
gfg1 = outer.inner
gfg1.show()
print()
gfg2 = outer.inner.innerclassofinner
gfg2.show()
Output
This is an outer class