0% found this document useful (0 votes)
37 views

Unit 4 Python L

The document discusses object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and encapsulation. It provides examples of defining classes and creating objects in Python to demonstrate these concepts.

Uploaded by

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

Unit 4 Python L

The document discusses object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and encapsulation. It provides examples of defining classes and creating objects in Python to demonstrate these concepts.

Uploaded by

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

UNIT 4 Python BY KANISHK SINGH

Python OOPs Concepts


In Python, object-oriented Programming (OOPs) is a programming paradigm that
uses objects and classes in programming. It aims to implement real-world entities
like inheritance, polymorphisms, encapsulation, etc. in the programming. The main
concept of OOPs is to bind the data and the functions that work on that together as a
single unit so that no other part of the code can access this data.
OOPs Concepts in Python
 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction

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

Creating an Empty Class in Python

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

The Python self


1. 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
2. If we have a method that takes no arguments, then we still have to have
one argument.
3. 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.
Note: For more information, refer to self in the Python class
The Python __init__ Method
The __init__ method is similar to constructors in C++ and Java. It is run 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. Now let us define a class and create some objects using
the self and __init__ method.

Creating a class and object with class and instance attributes

 Python3
class Dog:
# class attribute

attr1 = "mammal"

# Instance attribute

def __init__(self, name):

self.name = name

# Driver code

# Object instantiation

Rodger = Dog("Rodger")

Tommy = Dog("Tommy")

# Accessing class attributes

print("Rodger is a {}".format(Rodger.__class__.attr1))

print("Tommy is also a {}".format(Tommy.__class__.attr1))

# Accessing instance attributes

print("My name is {}".format(Rodger.name))

print("My name is {}".format(Tommy.name))

Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy

Creating Classes and objects with methods

Here, The Dog class is defined with two attributes:


 attr1 is a class attribute set to the value “mammal”. Class attributes are
shared by all instances of the class.
 __init__ is a special method (constructor) that initializes an instance of the
Dog class. It takes two parameters: self (referring to the instance being
created) and name (representing the name of the dog). The name
parameter is used to assign a name attribute to each instance of Dog.
The speak method is defined within the Dog class. This method prints a
string that includes the name of the dog instance.
The driver code starts by creating two instances of the Dog class: Rodger and
Tommy. The __init__ method is called for each instance to initialize their name
attributes with the provided names. The speak method is called in both instances
(Rodger.speak() and Tommy.speak()), causing each dog to print a statement with its
name.

 Python3
class Dog:

# class attribute

attr1 = "mammal"

# Instance attribute

def __init__(self, name):

self.name = name

def speak(self):

print("My name is {}".format(self.name))

# Driver code

# Object instantiation

Rodger = Dog("Rodger")

Tommy = Dog("Tommy")

# Accessing class methods

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

# __init__ is known as the constructor


def __init__(self, name, idnumber):

self.name = name

self.idnumber = idnumber

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

# invoking the __init__ of the parent class

Person.__init__(self, name, idnumber)

def details(self):

print("My name is {}".format(self.name))

print("IdNumber: {}".format(self.idnumber))

print("Post: {}".format(self.post))

# creation of an object variable or an instance

a = Employee('Rahul', 886012, 200000, "Intern")


# calling a function of the class Person using

# 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):

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

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

# demonstrate private members

# Creating a Base class

class Base:

def __init__(self):

self.a = "GeeksforGeeks"

self.__c = "GeeksforGeeks"

# Creating a derived class

class Derived(Base):

def __init__(self):
# Calling constructor of

# Base class

Base.__init__(self)

print("Calling private member of base class: ")

print(self.__c)

# Driver code

obj1 = Base()

print(obj1.a)

# Uncommenting print(obj1.c) will

# raise an AttributeError

# Uncommenting obj2 = Derived() will

# also raise an AtrributeError as

# private member of base class

# is called inside derived class

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}

Creating a Parent Class

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

def __init__(self, name, id):

self.name = name

self.id = id

# To check if this person is an employee

def Display(self):
print(self.name, self.id)

# Driver code

emp = Person("Satyam", 102) # An Object of Person

emp.Display()

Output:
Satyam 102

Creating a Child Class

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

print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function

Emp_details.Display()

# Calling child class function

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

# Base or Super class. Note object in bracket.

# (Generally, object is made ancestor of all classes)

# In Python 3.x "class Person" is

# equivalent to "class Person(object)"

class Person(object):

# Constructor

def __init__(self, name):

self.name = name

# To get name

def getName(self):

return self.name

# To check if this person is an employee

def isEmployee(self):

return False

# Inherited or Subclass (Note Person in bracket)

class Employee(Person):
# Here we return true

def isEmployee(self):

return True

# Driver code

emp = Person("Geek1") # An Object of Person

print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee

print(emp.getName(), emp.isEmployee())

Output:
Geek1 False
Geek2 True

Types of inheritance Python


Types of Inheritance in Python
Types of Inheritance depend upon the number of child and parent classes involved.
There are four types of inheritance in Python:
Single Inheritance:
Single inheritance enables a derived class to inherit properties from a single parent
class, thus enabling code reusability and the addition of new features to existing
code.
Example:
 Python3
# Python program to demonstrate

# single inheritance

# Base class

class Parent:

def func1(self):

print("This function is in parent class.")

# Derived class

class Child(Parent):

def func2(self):

print("This function is in child class.")


# Driver's code

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

class Son(Mother, Father):

def parents(self):

print("Father :", self.fathername)

print("Mother :", self.mothername)

# 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):

def __init__(self, fathername, grandfathername):

self.fathername = fathername

# invoking constructor of Grandfather class

Grandfather.__init__(self, grandfathername)

# Derived class

class Son(Father):

def __init__(self, sonname, fathername, grandfathername):

self.sonname = sonname

# invoking constructor of Father class

Father.__init__(self, fathername, grandfathername)

def print_name(self):

print('Grandfather name :', self.grandfathername)

print("Father name :", self.fathername)

print("Son name :", self.sonname)


# Driver code

s1 = Son('Prince', 'Rampal', 'Lal mani')

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

print("This function is in parent class.")

# Derived class1

class Child1(Parent):

def func2(self):

print("This function is in child 1.")

# Derivied class2

class Child2(Parent):

def func3(self):

print("This function is in child 2.")

# 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):

print("This function is in school.")

class Student1(School):

def func2(self):

print("This function is in student 1. ")


class Student2(School):

def func3(self):

print("This function is in student 2.")

class Student3(Student1, School):

def func4(self):

print("This function is in student 3.")

# Driver's code

object = Student3()

object.func1()

object.func2()

Output:
This function is in school.
This function is in student 1.

Why Choose Object Oriented Programming in Python?

Python was designed with OOP approach and it offers the following
advantages:

 Provides a clear program structure and a clean code


 Facilitates easy maintenance and modification of
existing code
 Since the class is sharable, the code can be reused
 Since the class is sharable, the code can be reused and
many other such Advantages.

Create Multiple Objects of Python Class

We can also create multiple objects from a single class. For example,

# define a class
class Employee:
# define an attribute
employee_id = 0

# create two objects of the Employee class


employee1 = Employee()
employee2 = Employee()

# access attributes using employee1


employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")

# access attributes using employee2


employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")
Run Code

Output

Employee ID: 1001


Employee ID: 1002

In the above example, we have created two


objects employee1 and employee2 of the Employee class.
Python Methods

We can also define a function inside a Python class. A Python


Function defined inside a class is called a method.
Let's see an example,

# create a class
class Room:
length = 0.0
breadth = 0.0

# method to calculate area


def calculate_area(self):
print("Area of Room =", self.length * self.breadth)

# create object of Room class


study_room = Room()

# assign values to all the attributes


study_room.length = 42.5
study_room.breadth = 30.8

# access method inside class


study_room.calculate_area()
Run Code

Output

Area of Room = 1309.0

In the above example, we have created a class named Room with:


 Attributes: length and breadth

 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

Earlier we assigned a default value to a class attribute,

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

Here, __init__() is the constructor function that is called whenever a new


object of that class is instantiated.
The constructor above initializes the value of the name attribute. We have
used the self.name to refer to the name attribute of the bike1 object.
If we use a constructor to initialize values inside a class, we need to pass
the corresponding value during the object creation of the class.

bike1 = Bike("Mountain Bike")

Here, "Mountain Bike" is passed to the name parameter of __init__() .


Creating Classes in Python
In Python, a class can be created by using the keyword class, followed by the class
name. The syntax to create a class is given below.

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:

1. # Declare an object of a class


2. object_name = Class_Name(arguments)

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:

"Hello, my name is Ayan"

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.

Inner Class in Python


Python is an Object-Oriented Programming Language, everything in python is
related to objects, methods, and properties. A class is a user-defined blueprint or a
prototype, which we can use to create the objects of a class. The class is defined by
using the class keyword.
Example of class
Python3

# create a Geeksforgeeks class

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

# create a Geeksforgeeks class

class Geeksforgeeks:

# constructor method

def __init__(self):

# object attributes

self.course = "Campus preparation"

self.duration = "2 months"


# define a show method

# for printing the content

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

print ('Name:', self.name)

# create Lightgreen class

class Lightgreen:

def __init__(self):

self.name = 'Light Green'

self.code = '024avc'

def display(self):

print ('Name:', self.name)

print ('Code:', self.code)

# create Color class object

outer = Color()
# method calling

outer.show()

# create a Lightgreen

# inner class object

g = outer.lg

# inner class method calling

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:

# Constructor method of outer class


def __init__(self):
self.NameOfVariable = Value

# create Inner class object


self.NameOfInnerClassObject = self.NameOfInnerClass()

# create a NameOfInnerClass class


class NameOfInnerClass:
# Constructor method of inner class
def __init__(self):
self.NameOfVariable = Value

# create object of outer class


outer = NameOfOuterClass()
Types of inner classes are as follows:
1. Multiple inner class
2. Multilevel inner class

Multiple inner class

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

# create outer class

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)

# create a 1st Inner class

class Dentist:

def __init__(self):

self.name = 'Dr. Savita'

self.degree = 'BDS'

def display(self):

print("Name:", self.name)

print("Degree:", self.degree)

# create a 2nd Inner class

class Cardiologist:

def __init__(self):

self.name = 'Dr. Amit'

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

# of 2nd inner class

d2 = outer.car

print()

d1.display()

print()

d2.display()

Output
In outer class
Name: Doctor

Name: Dr. Savita


Degree: BDS

Name: Dr. Amit


Degree: DM

Multilevel inner class

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

# create an outer class

class Geeksforgeeks:

def __init__(self):

# create an inner class object


self.inner = self.Inner()

def show(self):

print('This is an outer class')

# create a 1st inner class

class Inner:

def __init__(self):

# create an inner class of inner class object

self.innerclassofinner = self.Innerclassofinner()

def show(self):

print('This is the inner class')

# create an inner class of inner

class Innerclassofinner:

def show(self):

print('This is an inner class of inner class')

# create an outer class object

# i.e.Geeksforgeeks class object

outer = Geeksforgeeks()

outer.show()

print()

# create an inner class object

gfg1 = outer.inner
gfg1.show()

print()

# create an inner class of inner class object

gfg2 = outer.inner.innerclassofinner

gfg2.show()

Output
This is an outer class

This is the inner class

This is an inner class of inner class

You might also like