0% found this document useful (0 votes)
4 views23 pages

Python File Handling

The document covers file handling, classes, and objects in Python, detailing how to open, read, write, and append to files, as well as the use of classes and objects in object-oriented programming. It explains various file modes, methods for file operations, and the concept of data abstraction using abstract classes. Additionally, it provides examples of class definitions, object instantiation, and method calls within classes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

Python File Handling

The document covers file handling, classes, and objects in Python, detailing how to open, read, write, and append to files, as well as the use of classes and objects in object-oriented programming. It explains various file modes, methods for file operations, and the concept of data abstraction using abstract classes. Additionally, it provides examples of class definitions, object instantiation, and method calls within classes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON

PROGRAMMING

CHAPTER - IV
FILE HANDLING ,CLASSES AND
OBJECTS
MCA - I SEM

Prepared By:
[Link]
Lecturer of BCA
&MCA
Oxford college,
Hubli
2024-2025

1
File handling
 File handling in Python involves interacting with files on your computer to read data from
them or write data to them.
 Python provides several built-in functions and methods for creating, opening, reading,
writing, and closing files.

Opening a File in Python


To perform any file operation, the first step is to open the file. Python's built-in open()
function is used to open files in various modes, such as reading, writing, and appending. The
syntax for opening a file in Python is −
Syntax :
file = open("filename", "mode")

Common File Handling Operations in Python:


You use the open() function to open a file in different modes:
 'r': Read mode (default mode). Opens the file for reading.
 'w': Write mode. Opens the file for writing (creates a new file or overwrites an
existing one).
 'a': Append mode. Opens the file for appending data \(creates a new file if
doesn't exist).
 'b': Binary mode. Used when working with non-text files.
 'x': Exclusive creation. Creates a new file, but raises an error if the file already
exists.
Example :
# Opening a file in write mode
with open('[Link]', 'w') as file:
[Link]("Hello, this is a test file.\n")
[Link]("Python file handling is easy!\n")

# Opening a file in read mode


with open('[Link]', 'r') as file:
content = [Link]()
print(content)

# Appending data to the file


with open('[Link]', 'a') as file:
[Link]("This line is added to the file.\n")

# Reading the file again after appending


with open('[Link]', 'r') as file:
content = [Link]()
print(content)

Output:
Hello, this is a test file.
Python file handling is easy!

Hello, this is a test file.


Python file handling is easy!
This line is added to the file.

2
Reading a File in Python
Reading a file in Python involves opening the file in a mode that allows for reading, and then
using various methods to extract the data from the file. Python provides several methods to read
data from a file −
 read() − Reads the entire file.

 readline() − Reads one line at a time.

 Readlines() − Reads all lines into a list.

To read a file, you need to open it in read mode. The default mode for the open() function is read
mode ('r'), but it's good practice to specify it explicitly.
Example :
# Open the file in read mode
try:
with open('[Link]', 'r') as file:
# Read the entire content of the file
content = [Link]()
print("File content:\n")
print(content)

except FileNotFoundError:
print("The file does not exist.")

Output :
File content:

Hello, this is a test file.


Python file handling is easy!

Example for readline() and readlines()

with open('[Link]', 'r') as file:


line = [Link]() # Read first line
print(line)
line = [Link]() # Read second line
print(line)

with open('[Link]', 'r') as file:


lines = [Link]()
for line in lines:
print([Link]()) # strip() removes the newline character

Writing to a File in Python


 Writing to a file in Python involves opening the file in a mode that allows writing, and then
using various methods to add content to the file.
 To write data to a file, use the write() or writelines() methods. When opening a file in write
mode ('w'), the file's existing content is erased.

Example: Using the write() method


with open("[Link]", "w") as file:
[Link]("Hello, World!")
print ("Content added Successfully!!")

3
Output:
Content added Successfully!!

Example: Using the writelines() method


In here, we are using the writelines() method to take a list of strings and writes each string to the
file. It is useful for writing multiple lines at once −

lines = ["First line\n", "Second line\n", "Third line\n"]


with open("[Link]", "w") as file:
[Link](lines)
print ("Content added Successfully!!")

Output:
Content added Successfully!!

Binary File Handling:


Binary files store data in binary format (e.g., images, videos, executables). When working with
binary files, you need to use 'rb' (read binary) or 'wb' (write binary) modes.

Example :
# Writing binary data to a file
data = bytes([120, 3, 255, 0, 100]) # Binary data
with open('[Link]', 'wb') as file:
[Link](data)

# Reading binary data from a file


with open('[Link]', 'rb') as file:
data = [Link]() # Reads the entire content as bytes
print(data) # Output: b'x\x03\xff\x00d'

Note:
'rb': Read mode for binary files (reads in binary).

'wb': Write mode for binary files (writes in binary).

When you open a binary file, you read and write raw bytes, not characters.

CSV File Handling:


CSV (Comma Separated Values) files store tabular data in plain text, with each row of data
represented on a new line and columns separated by commas. Python provides the csv module
to work with CSV files.
Example :

import csv
# Reading from a CSV file
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row) # Each row is a list of values

# Writing to a CSV file


data = [['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles']]

with open('[Link]', 'w', newline='') as file:

4
writer = [Link](file)
[Link](data) # Write multiple rows

# Writing to a CSV file using dictionaries


data = [{'Name': 'Alice', 'Age': 30, 'City': 'New York'}, {'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'}]

with open('example_dict.csv', 'w', newline='') as file:


fieldnames = ['Name', 'Age', 'City']
writer = [Link](file, fieldnames=fieldnames)
[Link]() # Write header (column names)
[Link](data) # Write data

Closing a File in Python


We can close a file in Python using the close() method. Closing a file is an essential step in file
handling to ensure that all resources used by the file are properly released. It is important to
close files after operations are completed to prevent data loss and free up system resources.

Example
In this example, we open the file for writing, write data to the file, and then close the file using
the close() method −

file = open("[Link]", "w")


[Link]("This is an example.")
[Link]()
print ("File closed successfully!!")

Output:
File closed successfully!!

Using "with" Statement for Automatic File Closing


The with statement is a best practice in Python for file operations because it ensures that
the file is automatically closed when the block of code is exited, even if an exception occurs.

Example
In this example, the file is automatically closed at the end of the with block, so there is no
need to call close() method explicitly −

with open("[Link]", "w") as file:


[Link]("This is an example using the with statement.")
print ("File closed successfully!!")

Output:
File closed successfully!!

Handling Exceptions When Closing a File


 When performing file operations, it is important to handle potential exceptions to ensure
your program can manage errors gracefully.
 In Python, we use a try-finally block to handle exceptions when closing a file. The "finally"
block ensures that the file is closed regardless of whether an error occurs in the try block

5
try:
file = open("[Link]", "w")
[Link]("This is an example with exception handling.")
finally:
[Link]()
print ("File closed successfully!!")

Output:
File closed successfully!!

Here's a list of file handling modes in Python along with a brief description:

1. 'r' - Read Mode


Opens the file for reading. File must exist.

2. 'w' - Write Mode


Opens the file for writing. If the file exists, it will be overwritten. If not, a new file is
created.

3. 'a' - Append Mode


Opens the file for writing. Data is added to the end of the file. If the file doesn't exist,
a new file is created.

4. 'x' - Exclusive Creation Mode


Opens the file for exclusive creation. If the file already exists, an error is raised.

5. 'b' - Binary Mode


Opens the file in binary mode. It can be used with other modes (e.g., 'rb', 'wb').

6. 't' - Text Mode


Opens the file in text mode. This is the default mode and doesn't need to be
specified.

7. 'r+' - Read and Write Mode


Opens the file for both reading and writing. The file must exist.

8. 'w+' - Write and Read Mode


Opens the file for both writing and reading. If the file exists, it will be overwritten.

9. 'a+' - Append and Read Mode


Opens the file for both appending and reading. If the file doesn't exist, it will be
created.

10. 'b+' - Binary Read and Write Mode


Opens the file for both reading and writing in binary mode.

6
Python Classes and Objects
 We know that Python also supports the concept of objects and classes.
 An object is simply a collection of data (variables) and methods (functions).
 A class is a blueprint for that object and an object is an instance of a class.
 we can create many objects from a class.

Class
A class is a template or blueprint for creating objects (instances). It defines the attributes
(variables) and methods (functions) that objects of the class will have.

 __init_(_): This is a special method called a constructor that initializes objects of the
class. It's called when an object is created.

 self: A reference to the current instance of the class. It is used to access the object's
attributes and methods.
Syntax :
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

def method_name(self):
# Some operation or functionality
pass

Example :
class Car:
def __init__(self, make, model, year):
[Link] = make
[Link] = model
[Link] = year

def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}")

# Creating an object of the class 'Car'


my_car = Car("Toyota", "Corolla", 2020)
my_car.display_info()

Output:
2020 Toyota Corolla

Object:
An object is an instance of a class. When you create an object, you're using the class as a
blueprint to allocate memory and set initial values for the object's attributes.

Syntax :
object_name = ClassName(arguments)

7
Key concepts:
 Attributes: These are the variables associated with an object.
In the above example: make, model, and year are attributes of the Car class.
 Methods: These are functions defined inside a class that describe the behaviors of the
objects. In the above example, display_info is a method that displays
information about the car.

Example:
# Define a class called 'Car'
class Car:
def __init__(self, make, model, year):
# Initialize attributes of the class
[Link] = make
[Link] = model
[Link] = year

# Method to display car information


def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}")

# Create objects (instances) of the 'Car' class


car1 = Car("Toyota", "Corolla", 2020)
car2 = Car("Honda", "Civic", 2021)

# Access methods and attributes of the objects


car1.display_info()
car2.display_info() # Output:

Output:
2020 Toyota Corolla
2021 Honda Civic

Calling a class method from another class method in python


1: Calling a method from another method in the same class
class Car:
def start_engine(self):
print("Engine started.")
[Link]() # Calling the drive method from within the start_engine method

def drive(self):
print("The car is now driving.")

# Creating an instance of the Car class


my_car = Car()
my_car.start_engine() # Calling the start_engine method, which calls drive internally

Output:
Engine started.
The car is now driving.

8
2: Calling a method from another class
class Light:
def turn_on(self):
print("The light is turned on.")

def turn_off(self):
print("The light is turned off.")

class Room:
def __init__(self):
[Link] = Light() # Room has a Light object as an attribute

def enter_room(self):
print("Entering the room...")
[Link].turn_on() # Calling the turn_on method of the Light class

def leave_room(self):
print("Leaving the room...")
[Link].turn_off() # Calling the turn_off method of the Light class

# Creating an instance of Room


my_room = Room()
my_room.enter_room() # This calls the turn_on method from the Light class
my_room.leave_room() # This calls the turn_off method from the Light class

Output:
Entering the room...
The light is turned on.
Leaving the room...
The light is turned off.

Data Abstraction in Python


 Data abstraction is one of the fundamental concepts in Object-Oriented Programming
(OOP).
 It refers to the concept of hiding the complex implementation details of a system and
exposing only the necessary and relevant information to the user.
 In Python, data abstraction is implemented using abstract classes and abstract methods,
which are provided by the abc (Abstract Base Class) module.

Abstract Class:
 The classes that cannot be instantiated. This means that we cannot create objects of an
abstract class and these are only meant to be inherited. Then an object of the derived class
is used to access the features of the base class. These are specifically defined to lay a
foundation of other classes that exhibit common behavior or characteristics.
 The abstract class is an interface. Interfaces in OOP enable a class to inherit data and
functions from a base class by extending it.
 In Python, we use the NotImplementedError to restrict the instantiation of a class. Any
class having this error inside method definitions cannot be instantiated.
 Abstract Method: An abstract method is a method that is declared in the abstract class
but does not have a body or implementation. Subclasses must implement this method.

9
Syntax to implement data abstaction:

from abc import ABC, abstractmethod


class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass

Example:
from abc import ABC, abstractmethod
import math

# Abstract class
class Shape(ABC):
@abstractmethod
def area(self):
pass

# Concrete class for Circle


class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return [Link] * ([Link] ** 2)

# Concrete class for Rectangle


class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width

def area(self):
return [Link] * [Link]

# Trying to create an object of an abstract class will result in an error:


# shape = Shape() # This will raise an error because Shape is an abstract class.

10
# Creating objects of concrete classes
circle = Circle(5)
rectangle = Rectangle(4, 6)

print(f"Area of Circle: {[Link]()}")


print(f"Area of Rectangle: {[Link]()}")

Output:
Area of Circle: 78.53981633974483
Area of Rectangle: 24

Advantages of Data Abstraction:


 Simplification: Hides complex details and provides a simple interface.
 Maintainability: Changes in the internal implementation won't affect other parts of the
program.
 Flexibility: Allows for easy extensions. For example, you can add a new shape (like a triangle)
by just subclassing the Shape class and implementing the area() and perimeter() methods
without modifying other code.
 In summary, data abstraction helps create well-structured and modular code by focusing on
high-level operations while hiding the details of the implementation.

Encapsulation (Hiding through data )


 In Python, hiding data or implementation details through classes is generally achieved
through encapsulation.
 Encapsulation refers to the bundling of data (attributes) and the methods (functions) that
operate on that data, and restricting access to some of the object's components.
 This can prevent external code from directly modifying an object's internal state.
 In Python, data hiding is implemented using private attributes (with name mangling) and by
providing public methods (getters and setters) to interact with those attributes.
 This promotes good design principles, such as encapsulation and abstraction, helping to
create robust and maintainable code.

Why Hide Data?


Data Integrity: By hiding internal data, you prevent it from being modified directly, which can
lead to inconsistent or invalid states.
Controlled Access: You can control how attributes are modified (e.g., with validation or
transformation) via getter and setter methods.
Abstraction: Hiding the implementation details (like how the engine status is tracked) simplifies
the interface for users of the class.
Encapsulation: Helps with organizing code by bundling related data and behavior together,
improving maintainability.

Example :
class BankAccount:
def __init__(self, owner, balance):
self.__owner = owner # Private attribute
self.__balance = balance # Private attribute

# Public method to get balance (getter)


def get_balance(self):
return self.__balance

11
# Public method to deposit money (setter)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
else:
print("Invalid deposit amount.")

# Public method to withdraw money


def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew {amount}. New balance: {self.__balance}")
else:
print("Invalid withdrawal amount or insufficient funds.")

# Create an instance of the BankAccount class


account = BankAccount("Alice", 1000)

# Accessing balance through the public method


print("Initial Balance:", account.get_balance())

# Deposit some money


[Link](500)

# Withdraw some money


[Link](200)

Output:
Initial Balance: 1000
Deposited 500. New balance: 1500
Withdrew 200. New balance: 1300

Data members :
In Python, data members (also known as attributes) are variables that belong to a class and are
used to store data for instances of that class. These data members can either be instance
variables or class variables depending on their scope and usage.

1. Instance Variables (data members specific to an instance)


 Instance variables are tied to a specific object (instance) of the class.
 They are defined inside the constructor (__init__) or other methods and use self to
differentiate each object.
 Instance variables are specific to each object. Each object can have different values for
these variables.

2. Class Variables (data members shared by all instances)


 Class variables are shared across all instances of the class.
 They are defined within the class, but outside any instance methods.
 Class variables are shared by all instances of the class, meaning if the value of a class
variable is changed, it affects all instances of the class.

12
Class methods and static methods
In Python, class methods and static methods are types of methods that are defined within a class,
but they behave differently from regular instance methods.

Class Methods
 Class methods are methods that are bound to the class rather than its objects. They can
access and modify class-level variables.
 Class methods take a special first argument called cls, which refers to the class itself (not an
instance of the class).
 To define a class method, you use the @classmethod decorator.

When to use class methods:


 When you want a method that operates on the class itself rather than on instances.
 When you need to modify class-level variables.

Example :
class Dog:
species = "Canis familiaris" # Class variable

def __init__(self, name):


[Link] = name

@classmethod
def change_species(cls, new_species):
[Link] = new_species # Modify the class variable

@classmethod
def print_species(cls):
print(f"Species: {[Link]}")

dog1 = Dog("Buddy")
dog2 = Dog("Bella")

# Calling the class method to change the class-level variable


Dog.change_species("Canis lupus familiaris")

# Calling the class method to print the class-level variable


dog1.print_species()
dog2.print_species()

# Verifying that both dog1 and dog2 share the same class-level variable value

Output:
Species: Canis lupus familiaris
Species: Canis lupus familiaris

Note:
In this above example ,change_species is a class method that modifies the class-level variable
[Link] dog1 and dog2 share the modified species variable.

13
Static Methods
 Static methods do not operate on the class or instance. They don't have access to self or cls.
 They are just functions that belong to the class namespace.
 Static methods are defined using the @staticmethod decorator.
 Static methods are used when you need a function that logically belongs to the class but
does not need to access or modify the class or instance.

Example :
class Math:

@staticmethod
def add(x, y):
return x + y

@staticmethod
def multiply(x, y):
return x * y

# Calling static methods without creating an instance of the class


print([Link](5, 3))
print([Link](4, 7))

Output:
8
28

Note:
In this above example , add and multiply are static methods because they don’t require access to
either the class or instance. They just perform a computation.

Key Differences:
Feature Instance Method Class Method Static Method
First
self (refers to Instance) cls (refers to the class) None (doesn’t take self or cls)
argument
Class variables and Neither instance nor class
Accesses Instance variables and methods
methods variables, just data
Works on class-level Utility functions that don't
Use case Works on instance-level data
data depend on instance or class
Decorator None (just a normal method) @classmethod @staticmethod
When you need to When you need a utility
When you need to operate on operate on class-level function that logically belongs
When to
data that is specific to a data or when you want to the class but does not
use each
particular object (instance). to modify class-level need access to any class or
class
variables, or use the instance-specific data.
class as a factory
method.

14
Inheritance
 Inheritance is a fundamental concept in object-oriented programming (OOP) in Python,
allowing one class (the subclass or child class) to inherit attributes and methods from
another class (the superclass or parent class).
 It is used to inherit the properties and behaviours of one class to another.
 The class that inherits another class is called a child class and the class that gets inherited is
called a base class or parent class.
 This enables code reuse and can help structure programs in a more modular and organized
way.
Benefits of Inheritance:
 Code Reusability: We can reuse the code in the parent class without rewriting it in the child
class.
 Extensibility: We can easily extend the functionality of the parent class by adding new
methods or modifying existing ones in the child class.

Creating a Parent Class


The class whose attributes and methods are inherited is called as parent class. It is defined just
like other classes i.e. using the class keyword.

Syntax
class ParentClassName:
{class body}

Creating a Child Class


Classes that inherit from base classes are declared similarly to their parent class, however, we
need to provide the name of parent classes within the parentheses.

Syntax
class SubClassName (ParentClass1[, ParentClass2, ...]):
{sub class body}

Types of Inheritance
In Python, inheritance can be divided in five different categories −
 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid inheritance

15
Single Inheritance
This is the simplest form of inheritance where a child class inherits attributes and methods from
only one parent class.
Syntax :
# Parent Class (Super class)
class ParentClass:
# statements

# Child Class (Sub class)


class ChildClass(ParentClass):
# statements

Example :
# Parent class (Super class)
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
return f"{[Link]} makes a sound."

# Child class (Sub class) inheriting from Animal


class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call to the parent class constructor
[Link] = breed

# Overriding the speak method of the parent class


def speak(self):
return f"{[Link]} says Woof!"

# Creating an instance of the Dog class


dog = Dog("Buddy", "Golden Retriever")

# Calling methods from both parent and child classes


print([Link]())

Output:
Buddy says Woof!

Multiple Inheritance
 Multiple inheritance in Python allows you to construct a class based on more than one
parent classes.
 The Child class thus inherits the attributes and method from all parents. The child can
override methods inherited from any parent.
Syntax :
class parent1:
#statements

class parent2:
#statements

class child(parent1, parent2):


#statements

16
Method Resolution Order (MRO)
The term method resolution order is related to multiple inheritance in Python. In Python, inheritance
may be spread over more than one levels. Let us say A is the parent of B, and B the parent for C. The
class C can override the inherited method or its object may invoke it as defined in its parent. So, how
does Python find the appropriate method to call.

Each Python has a mro() method that returns the hierarchical order that Python uses to resolve the
method to be called. The resolution order is from bottom of inheritance order to top.

Multilevel Inheritance
In multilevel inheritance, a class is derived from another derived class. There exists multiple layers of
inheritance. We can imagine it as a grandparent-parent-child relationship.

Syntax :
# Parent Class (Super class)
class GrandparentClass:
# statements

# Child Class (Subclass of Grandparent)


class ParentClass(GrandparentClass):
# statements

# Grandchild Class (Subclass of Parent)


class ChildClass(ParentClass):
# statements

Example :
# parent class
class Universe:
def universeMethod(self):
print ("I am in the Universe")

# child class
class Earth(Universe):
def earthMethod(self):
print ("I am on Earth")

# another child class


class India(Earth):
def indianMethod(self):
print ("I am in India")

# creating instance
person = India()

# method calls
[Link]()
[Link]()
[Link]()

Output :
I am in the Universe
I am on Earth
I am in India

17
Hierarchical Inheritance
This type of inheritance contains multiple derived classes that are inherited from a single base class.
This is similar to the hierarchy within an organization.

Syntax :
# Parent Class (Super class)
class ParentClass:
# statements

# First Child Class (Subclass of ParentClass)


class ChildClass1(ParentClass):
# statements

# Second Child Class (Subclass of ParentClass)


class ChildClass2(ParentClass):
#statements

Example :
# parent class
class Manager:
def managerMethod(self):
print ("I am the Manager")

# child class
class Employee1(Manager):
def employee1Method(self):
print ("I am Employee one")

# second child class


class Employee2(Manager):
def employee2Method(self):
print ("I am Employee two")

# creating instances
emp1 = Employee1()
emp2 = Employee2()
# method calls
[Link]()
emp1.employee1Method()
[Link]()
emp2.employee2Method()

Output :
I am the Manager
I am Employee one
I am the Manager
I am Employee two

18
Hybrid Inheritance
Combination of two or more types of inheritance is called as Hybrid Inheritance. For instance, it could
be a mix of single and multiple inheritance.

Syntax :
# Parent Class 1 (Super class)
class ClassA:
# statements
# Parent Class 2 (Super class)
class ClassB:
# statements

# Child Class 1 (inherits from both ClassA and ClassB)


class ClassC(ClassA, ClassB):
# statements

# Child Class 2 (inherits from ClassC)


class ClassD(ClassC):
# statements

The super() function


In Python, super() function allows you to access methods and attributes of the parent class from
within a child class.

Example :
# parent class
class ParentDemo:
def __init__(self, msg):
[Link] = msg

def showMessage(self):
print([Link])

# child class
class ChildDemo(ParentDemo):
def __init__(self, msg):
# use of super function
super().__init__(msg)

# creating instance
obj = ChildDemo("Welcome to Python!!")
[Link]()

Output :
Welcome to Python!!

19
Python - Interfaces
In software engineering, an interface is a software architectural pattern. It is similar to a class but
its methods just have prototype signature definition without any executable code or
implementation body. The required functionality must be implemented by the methods of any
class that inherits the interface.

In languages like Java and other, there is keyword called interface which is used to define an
interface , But Python doesn't have it or any similar keyword. It uses abstract base classes (in
short ABC module) and @abstractmethod decorator to create interfaces.

In Python, abstract classes are also created using ABC module.

An abstract class and interface appear similar in Python. The only difference in two is that the
abstract class may have some non-abstract methods, while all methods in interface must be
abstract, and the implementing class must override all the abstract methods.

Rules for implementing Python Interfaces


 Methods defined inside an interface must be abstract.
 Creating object of an interface is not allowed.
 A class implementing an interface needs to define all the methods of that interface.
 In case, a class is not implementing all the methods defined inside the interface, the class
must be declared abstract.

Two ways to implement Interfaces in Python


 Formal Interface
 Informal Interface

Formal Interface
Formal interfaces in Python are implemented using abstract base class (ABC). To use this class,
you need to import it from the abc module.
Example :
from abc import ABC, abstractmethod

# creating interface
class demoInterface(ABC):
@abstractmethod
def method1(self):
print ("Abstract method1")
return

@abstractmethod
def method2(self):
print ("Abstract method1")
return

# class implementing the above interface


class concreteclass(demoInterface):
def method1(self):
print ("This is method1")
return
def method2(self):
print ("This is method2")
return

20
# creating instance
obj = concreteclass()

# method call
obj.method1()
obj.method2()

Output:
This is method1
This is method2

Informal Interface
In Python, the informal interface refers to a class with methods that can be overridden. However,
the compiler cannot strictly enforce the implementation of all the provided methods.

This type of interface works on the principle of duck typing. It allows us to call any method on an
object without checking its type, as long as the method exists.

Example:
class demoInterface:
def displayMsg(self):
pass

class newClass(demoInterface):
def displayMsg(self):
print ("This is my message")

# creating instance
obj = newClass()

# method call
[Link]()

Output :
This is my message

Python - Method Overloading :


Method overloading is a feature of object-oriented programming where a class can have multiple
methods with the same name but different parameters. To overload method, we must change
the number of parameters or the type of parameters, or both.

Unlike other programming languages like Java, C++, and C#, Python does not support the
feature of method overloading by default. However, there are alternative ways to achieve it.

If you define a method multiple times,the last definition will override the previous ones.
Therefore, this way of achieving method overloading in Python generates error.

To simulate method overloading, we can use a workaround by defining default value to method
arguments as None, so that it can be used with one, two or three arguments.

21
Example :
class example:
def add(self, a = None, b = None, c = None):
x=0
if a !=None and b != None and c != None:
x = a+b+c
elif a !=None and b != None and c == None:
x = a+b
return x

obj = example()

print ([Link](10,20,30))
print ([Link](10,20))

Output :
60
30

Implement Method Overloading Using MultipleDispatch


Python's standard library doesn't have any other provision for implementing method overloading.
However, we can use a dispatch function from a third-party module named MultipleDispatch for
this purpose.

First, you need to install the Multipledispatch module using the following command −
pip install multipledispatch
This module has a @dispatch decorator. It takes the number of arguments to be passed to the
method to be overloaded. Define multiple copies of add() method with @dispatch decorator as
below −
Example :
from multipledispatch import dispatch
class example:
@dispatch(int, int)
def add(self, a, b):
x = a+b
return x
@dispatch(int, int, int)
def add(self, a, b, c):
x = a+b+c
return x

obj = example()

print ([Link](10,20,30))
print ([Link](10,20))

Output:
60
30

22
Python - Method Overriding
The Python method overriding refers to defining a method in a subclass with the same name as a
method in its superclass. In this case, the Python interpreter determines which method to call at
runtime based on the actual object being referred to.

You can always override your parent class methods. One reason for overriding parent's methods
is that you may want special or different functionality in your subclass.

Example :
In the code below, we are overriding a method named myMethod of Parent class.
# define parent class
class Parent:
def myMethod(self):
print ('Calling parent method')

# define child class


class Child(Parent):
def myMethod(self):
print ('Calling child method')

# instance of child
c = Child()
# child calls overridden method
[Link]()

Output :
Calling child method

Base Overridable Methods


The following table lists some generic functionality of the object class, which is the parent class
for all Python classes. You can override these methods in your own class −

[Link] Method, Description & Sample Call

__init__ ( self [,args...] )


1 Constructor (with any optional arguments)
Sample Call : obj = className(args)

__del__( self )
2 Destructor, deletes an object
Sample Call : del obj

__repr__( self )
3 Evaluatable string representation
Sample Call : repr(obj)

__str__( self )
4 Printable string representation
Sample Call : str(obj)

23

You might also like