Mastering Python File Handling: Essential Techniques for Efficient Data Management

python file

File handling in Python refers to the process of CRUD operations i.e., creating, reading, updating, and deleting files using the built-in file operations in Python.

In this blog you will be able to understand the creation of file and different operations performed on python files.

Files are used for storing information and handling of these files are important aspect to learn. Python file handling is a simple aspect when you follow this tutorial and practice the operations specified.

We can observe files are being created in this example and extension of python file is of type .txt i.e., text format.Also we can run a python file after it get’s created.

Python File Handling Video Tutorial :

You can find all the above stated examples in this video tutorial.

Create a file :

Creating a file and adding some data. Here you can also notice the python file extension which is specified with file name before.

Make sure you specify correct extension of python file such that you can open / read it after it’s creation. Also you need to perform python file close after every write or append.

To write to a file, open the file in write mode and use the write() method to write data to the file.

Here we have specified ‘x’ such that it creates the file after opening the file rather than reading.

f = open('file.txt', 'x')

f.write('python')

f.close()

Read a file :

To open a file in Python, use the open() function. The open() function takes two parameters, the filename and the mode in which you want to open the file.

Once the file is opened, you can read its contents. There are several methods to read a file in Python. The most common one is the read() method, which reads the entire file.

Reading a file which we have created by logging python file in console you can find output as shown below.Also you can see ‘r’ which specifies read is performed.

f = open('file.txt', 'r')

print(f.read())

output :

python

Append a file :

Adding some extra information to the file which we have created and python file close is performed after it.Then when you read the information complete data is printed with old and new changes.

Here we have specified ‘a’ such that it appends the information after opening the file rather than reading.

f = open('file.txt', 'a')

f.write(' program')

f.close()

Close a file:

It is essential and good practice to close a file after reading or writing to it. You can do this using the close() method.Can observe in our examples we have closed all the files after the use.

f.close()

Exception handling:

Handling errors are most important to make a error free software When working with files, errors can occur. To handle these errors, you can use a try-except block.

Not only in files this handling can be used to handle errors through out the code.

If you have any query’s in this tutorial on file handling do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates..

Go through the complete python course video tutorial’s here for detailed implementation.

python file

Python Scope Mastery: Unleashing the essential Variables and Methods

Python scope plays a vital role in app implementation for example if you have declared a variable a in a class then you can use the same variable multiple times but you can’t declare another variable with same name.

i..e, when you declare a variable globally this will be the scenario but when you declare a variable locally you can create multiple variables with same name.

If you are a beginner and finding it difficult to understand what is a variable ?? is suggest you to go through this blog on variables.

In short scope is the extent upto which a variable can be used and reached i.e., once the variable is out of scope then you cannot access it any more.

Let us see an example through which you can understand the implementation of python scope.

Python scope video tutorial :

You can find all the above stated examples in this video tutorial.

Local Scope :

Local scope is within the scope where it is declared confined to that particular block of code locally. A local scope is a part of a program where variables are defined and can only be accessed within that particular scope.

A local scope can be created within a function or a block of code.

def abc():
   
    x = 10;
    print(x)

abc()

output :

10

Now declare the block of code where we have nested function

def abc():
   
    x = 10;
    def abcd():
        print(x)

    abcd()

abc()

Now still you will be able to see 10 as output.

output :

10

Global Scope :

Global scope is through out the class we can make it available irrespective of a function where it is used. These variables are defined outside a function or block of code and can be accessed within the function or block of code as well as outside of it.

It’s important to note that variables defined outside of a function or block of code have a global scope and can be accessed anywhere in the program. However, if a variable with the same name is defined within a local scope, it will take precedence over the global variable within that scope.

x = 10

def abc():
   
    print(x)

abc()

Here the variable is declared outside the function i.e., globally and used inside the function.

Local Vs Global Scope :

When you declare a global variable and also local variable with same name local variable replaces global one.

The main difference between local scope and global scope is the accessibility of the variables. Variables defined within a local scope can only be accessed within that particular scope, while variables defined within a global scope can be accessed anywhere in the program.

Another difference between local and global scope is that if a variable is defined within a local scope with the same name as a global variable, it will take precedence over the global variable within that scope. To modify a global variable within a local scope, the global keyword can be used.

x = 10;

def abc():
   
    x = 12;
    def abcd():
        print(x)

    abcd()

abc()

output :

12

Usage try to restrict the usage of variables locally and if required to be used every where in app then declare them globally and again security constraints to be taken care.

If you have any query’s in this tutorial on python scope do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates..

Go through the complete python course video tutorial’s here for detailed implementation.

python scope

Python Sorting

Python sorting concept helps you to arrange the values in a specific order there are various sorting mechanisms in python out of which merge sort is mostly used.

In this blog as a beginners guide on sorting let us discuss on ascending or descending ways of sorting. So what is the use of these ordering ??

In real time scenarios when you want to arrange the things in a proper way it will be easy to arrange data of limited size but when there is a huge data it’s almost difficult to sort.

Sorting again is depend on various factors in shopping apps we can sort products by availability , price, offers so on.. These sorting help us to identify the products easily.

Arranging a set of students data according to there roll no is one of the example we can consider. There are several sorting algorithms available, each with its advantages and disadvantages, depending on the specific use case.

The choice of which sorting algorithm to use depends on the specific use case and the properties of the input data.

So now let us see how this thing works with the help of a example where we have list of numbers and we arrange it in this blog on python sorting let us see ascending order, descending order with functions declared.

Ascending Order :

Specifying sort will by default make it ascending order i.e., from lower value to higher value as shown below.

Ascending order refers to the arrangement of elements in increasing order. For example, if you have a list of numbers then [ 1,2,4,5 ], arranging them in ascending order means that the new list would be [ 4,2,5,1 ].

In programming, sorting a list of elements in ascending order is a common operation. In Python, you can use the built-in sort() method or the sorted() function to sort a list in ascending order.

a = [ 4, 2, 5, 1 ]

a.sort()

output :

[ 1, 2, 4, 5 ]

Descending Order :

Specify the reverse = true to order the list of variables from higher value to lower value i.e., descending order then print it.

Descending order refers to the arrangement of elements in decreasing order. For example, if you have a list of numbers [ 4, 2, 5, 1 ], arranging them in descending order means that the new list would be [ 5, 4, 2, 1 ].

a = [ 4, 2, 5, 1 ]

a.sort( reverse = True  ) 

print( a )

output :

[ 5, 4, 2, 1 ]

Not only numbers we can also sort alphabets and also words with this sorting mechanism

b = [ 'b', 'a', 'z', 'g' ]

b.sort( ) 

print( b )

output :

[ 'a', 'b', 'j', 'z' ]

Python Sorting Function :

We can create a sorting function such that it returns the length. This is just an example you can create your own functions based on your requirement.

Python provides a built-in sorting function sorted() that can be used to sort a list of elements in ascending or descending order. The sorted() function returns a new list with the sorted elements, leaving the original list unmodified.

def sortfunction(e) :
       return len(e)

Python Sorting Video Tutorial :

Implementation of this function is clearly explained in the video tutorial below go through it.

If you have any query’s in this tutorial on python sorting do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates..

Boosting Performance with Python Multithreading: A Guide to Efficient Parallel Execution

python multithreading

Python Multithreading concept makes it easier for both programmers and end users to get the work done in less amount of time.

Yes in simple what is python multithreading ? performing more than one task at once so that we can make a good use of available time and can provide much faster.

In technical aspects we can say that concurrent execution more than one process in a given amount of time making the proper use of available resources.

Multithreading is a programming technique that allows multiple threads of execution to run concurrently within a single process. In Python, you can use the threading module to create and manage threads.

The threading module provides a Thread class that you can subclass to create new threads. You can also use the Thread class directly to create threads.

Now a days computer is used in almost all the fields. Multithreading plays a key role in the usage of computers all over.Again not only computers but all other gadgets as well like mobile too which we use.

Python Multithreading Video Tutorial :

Implementation of python multithreading is clearly explained in the video tutorial below go through it.

Let’s try to consider a basic example of multi threading.

class Greeting:

       def run(self):
             for i in range(5):
                    print("Welcome")
       

And another class with names and tried to append number to names.

class Names:

       def run(self):
             for i in range(5):
                    print("Henry" + i+1)
       

We have added i + 1 to avoid 0.

Create objects for the two classes

h1 = Greeting()
h2 = Names()

Now run these two classes using objects

h1.run()
h2.run()

output :

Now let us try to run this code and observe how the code runs.Till the time first method completes it execution second method is waiting for it turn to get started.

Welcome
Welcome
Welcome
Welcome
Welcome
Henry 1
Henry 2
Henry 3
Henry 4
Henry 5

Python Multithreading Example :

Let us make use of multithreading here in this example now.

Make use of threading concept to make multithreading. Import the thread and extend it to the classes as below.

In Python, you can use the threading module to create and manage threads. The threading module provides a Thread class that you can subclass to create new threads, or you can use the Thread class directly to create threads. You can pass a target function to the Thread constructor, which will be run in a separate thread when you call the start() method.

from threading import Thread
from time import Sleep

class Greeting(Thread):

       def run(self):
             for i in range(5):
                    print("Welcome ")
                    sleep(1)

class Names:

       def run(self):
             for i in range(5):
                    print(" Henry" + i+1)
       

Now we need to start thread instead of run

h1.start()
h2.start()

output:

Now that we have added sleep(1) and tried to start thread observe output there is a slight delay such that both the methods run in parallel.

Welcome 
Henry 1
Welcome 
Henry 2
Welcome 
Henry 3
Welcome 
Henry 4
Welcome 
Henry 5

To synchronize access to shared resources between threads, you can use synchronization primitives such as locks, semaphores, and condition variables provided by the threading module.

Note that Python also provides a higher-level multiprocessing module that allows you to create and manage multiple processes instead of threads. This can be useful in cases where parallelism needs to be achieved across multiple CPU cores or machines.

If you have any query’s in this tutorial on python multithreading do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates..

Go through the video tutorial for detailed implementation.Watch the complete video course on python.

python multithreading

Python Exceptional Handling

python exceptional handling

Python exceptional handling will provide a smooth and crash free user experience by properly handling the unexpected crashes in your app.

An exception is an event that occurs during the execution of a program that disrupts the normal flow of the program’s instructions. When an exception occurs, the program terminates the current operation and jumps to a pre-defined exception handling routine.

In software apps crashing is the most common scenario faced by almost every app. No app is build with a 100% crash free usage.

It’s not like inefficiency in coding but the device, network and other parameters also affects the functioning of the app.

We need to handle these crashes efficiently using a standard approach provided by python, because some times it might be abnormal to stop a user flow and losing data due to app closure.

Some common types of exceptions include:

ArithmeticException :

We find this mostly in calculations, As this exception is thrown when an arithmetic operation produces an error, such as dividing by zero.

NullPointerException :

When any value is missing or null received this exception is thrown such as when a program attempts to use a null object reference.

IOException :

When the file is not accessible or database this exception is thrown stating that an input or output operation failed.

IllegalArgumentException :

When the argument passed is invalid or doesn’t match the type this exception is thrown.

RuntimeException:

This is a most common general-purpose exception class that can be used to represent a wide range of runtime errors, such as memory insufficient, index out of bounds error.

Python Exceptional Handling Video Tutorial :

Watch the video tutorial on exception handling in python.

Let us see an example

a = 10
b = 5

print(a/b)

output :

2

Now let us try to see the same example where we get an error

a = 10
b = 0

print(a/b)

output:

Can you guess this output ?? We will be getting a ZeroDivisionError : divide by zero.

How to handle these errors ?

Errors make a big flaw in app functionality i..e, it stops user flow and ends the app some times it might lose app state and data user entered too.

You can make use of Try Except in handling your errors.

In Try block you will be trying the code which is vulnerable to crash

In Except block you will handle it such that crash won’t happen and also display a message stating the issue happened.

a = 10
b = 0

try :
    print(a/b)

except Exception:
    print("You have got an error")

Output:

Now you will not get any error and a message is displayed instead.

Also you can make use of finally block i have explained its usage clearly in video tutorial.

Therefore a proper handling of exceptions is an important part of writing robust and reliable software. By anticipating and handling exceptions, developers can create programs that are more resilient and less prone to errors.

If you have any query’s in this tutorial on Python Exceptional Handling do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates..

Go through the video tutorial for detailed implementation.Watch the complete video course on python.

python exceptional handling

Python Method Overriding

Python method overriding is a similar concept like we do in terms of Method Overloading. Here we make use of a method with the same name multiple times in multiple classes.

If you want to alter the behaviour of the method according to your requirement yes it’s possible i.e., you don’t want to make use of parent class implementation.

Here you will have the freedom to override the method functionality with the requirement in the child class specified.

Method overriding is a feature of object oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its superclass.

When a method in a subclass has the same name, return type, and parameter list as a method in its superclass, the method in the subclass overrides the method in the superclass.

When an object of the subclass calls the overridden method, the specific implementation in the subclass is executed instead of the implementation in the superclass. This allows subclasses to provide a specialized implementation of a method inherited from its superclass, while still retaining the same interface.

To override a method in a subclass, the method in the subclass must have the same signature (name, return type, and parameter list) as the method in the superclass. Additionally, the access level of the method in the subclass cannot be more restrictive than the access level of the method in the superclass.

This concept also makes it flexible for you to perform code reuse which will have a lot of advantages like faster processing, less memory consumption and much more…

Python Method Overriding Video Tutorial :

Go through the below tutorial for more detailed explanation of Method Overriding.

Create a class A and add a print statement in method display

Class A:
    def display():
        print("I am class A")

Let’s try to create an object for it and print the data

c = A()
c.display()

output:

I am class A

Now let us create a new class B so that we can know the implementation of Method Overriding

Class B:
    a = 10

Create a object for class B. Now try to call the method display here.

c = B()
c.display()

You will get a error because display method is not there in class B

Now inherit class A on class B

Class B(A):
    a = 10

Now try to call display method which is intern extended by class A

c = B()
c.display()

output: We can observe display method is printed which was declared in class A.

I am class A

Here we are making use of the inheritance concept and providing method overriding functionality.

And now what if i want to change the message in class B that is to be printed ??

Class B(A):
    def display():
        print("I am class B")

make use of the object and call display

c = B()
c.display()

here though we are inheriting class A but we do have a display method in class B so we consider it.

output:

I am class B

Can we inherit multiple classes and fetch their methods ???

I have clearly explained in the video tutorial so suggest you to go through it.


If you have any query’s in this implementation of python method overriding do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates.

Python Method Overloading

Python Operator Overloading

Python method overloading is explained in this blog using some of the interesting examples so that you can grasp the concept in a easy way.

Python Method Overloading is by default not available but we will be seeing how to implement it in different way.

Method overloading is a feature of object oriented programming that allows multiple methods with the same name to be defined in a class, as long as they have different parameters.

When a method is called, the compiler determines which version of the method to call based on the number, type, and order of the arguments passed in.

In method overloading, each method has a unique signature, which is defined by the method name and the number, type, and order of its parameters. This allows developers to create methods with the same name that perform similar tasks but with different input parameters. This makes the code more concise, readable, and maintainable.

You might have gone through method overloading concept in other programming languages like C but in python the usage is a bit different.

Unlike some other object-oriented programming languages like Java, Python does not support method overloading in the traditional sense. In Python, you can define multiple functions or methods with the same name, but Python does not select the appropriate version of the method to call based on the number, type, or order of the arguments passed in. Instead, the last version of the method defined with the same name overwrites the previous one.

However, Python provides a way to simulate method overloading using default arguments and variable-length argument lists.

Python selects the appropriate version of the method to call based on the number and type of the arguments passed in.

While this technique allows you to simulate method overloading in Python, it is not as robust or intuitive as the method overloading found in other programming languages.

Therefore, it is generally recommended to use different method names or to document the different behavior of each method if you need to provide multiple versions of the same method in Python.

In our previous tutorial we have seen the operator overloading concept to customize the addition operator to perform addition of two objects rather than numbers.

Python Method Overloading Video Tutorial :

Go through this tutorial for more detailed explanation of this concept.

Let’s create a class

Class A :
    def add(self, n1, n2, n3):
        result n1 + n2 + n3
        return result;

a1 = A()
print(a1.add(1, 2, 3))

output:

So when you try to run this code you will get the below output

6

Now let us try to make use of the method overloading concept and use the same function and send one or more (max 3) parameters but get the accurate calculation done.

Here we will be considering 3 scenarios where parameters differ like 3 passed at once, 2 and finally 1 parameter passed but we don’t get any error.

Class A :
    def add(self, n1 = None, n2 = None, n3 = None):
        if n1 is not None and n2 is not None and n3 is not None: 
            result n1 + n2 + n3
        elif n1 is not None and n2 is not None:
            result n1 + n2 
        else
            result n1
        return result;

Now let us try method overloading

create a object

a1 = A()

Try to pass 3 parameters

print(a1.add(1, 2, 3))

output:

6

Now try to pass 2 parameters

print(a1.add(1, 2))

output:

3

Now finally pass one parameter

print(a1.add(1))

output:

1

If you have any query’s in this tutorial on Python Method Overloading do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates..

Go through the video tutorial for detailed implementation.

Python Operator Overloading

The concept of python operator overloading is used almost in every programming where you can find that we are able to add additional functionality to a existing method.

Python Operator Overloading why is it used ?? how to understand it in much simpler way get started with this blog now

Sometimes we require function name to be same but be dynamic in doing various tasks by accepting multiple or different parameters at this scenario python operator overloading comes into picture.

Operator overloading is a feature in programming languages that allows you to redefine the behavior of an operator when it is applied to instances of your classes. In Python, you can overload many of the built-in operators by implementing special methods in your class definition.

Overloading operators can make your code more concise and easier to read by allowing you to write code that is more natural and intuitive. For example, you can overload the + operator to concatenate two strings, the - operator to subtract two numbers, or the * operator to multiply two matrices.

To overload an operator in Python, you need to define a special method with a name that corresponds to the operator you want to overload. The name of the method is surrounded by double underscores and is called a magic method or dunder method. For example, to overload the + operator, you need to define the __add__() method in your class.

Python allows the operator overloading feature, which means that you can redefine the behavior of some built-in operators when they are applied to instances of your classes. This is achieved through special methods in Python called magic or dunder methods (double underscore methods) or sometimes referred to as “special methods”.

Python allows the operator overloading feature, which means that you can redefine the behavior of some built-in operators when they are applied to instances of your classes. This is achieved through special methods in Python called magic or dunder methods (double underscore methods) or sometimes referred to as “special methods”.

Here are some of the most commonly used magic methods for operator overloading:

__add__(self, other) : Defines the behavior of the addition operator + when applied to instances of your class.

__sub__(self, other) : Defines the behavior of the subtraction operator - when applied to instances of your class.

__mul__(self, other) : Defines the behavior of the multiplication operator * when applied to instances of your class.

__truediv__(self, other) : Defines the behavior of the division operator / when applied to instances of your class.

Python Operator Overloading Video Tutorial :

Go through the below vlog for detailed instructions on implementations.

We can consider a basic example like

a = 10
b = 12

print(a+b)

output :

22

If you try to observe what happening in the below line of code

print(a+b)

has the real implementation like below

print( int.__add__(a, b))

OK so far so clear but what is method overloading ???

We will create a class and try to add two objects instead of numbers i.e., through variables.

Class A:
      def __init__(self, n1, n2):
          self.n1 = n1
          self.n2 = n2

And now with the help of class we will add numbers for which let us create objects.

a1 = A(1, 2)
a2 = A(3, 4)

Now try to print the output

You will be getting a error like type not supported.

Class A:
      def __init__(self, n1, n2):
          self.n1 = n1
          self.n2 = n2
    
      def __add__(self, other):
          t1 = self.n1 + other.n1
          t2 = self.n2 + other.n2

          return t1, t2

now try to print

print(a1 + a2)
a1 = A(1, 2)
a2 = A(3, 4)

output :

(4, 6)

If you have any query’s in this tutorial on Python Operator Overloading do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates..

Python Operator Overloading

Unlocking the Power of Python Encapsulation: Best Practices and Examples

Python Encapsulation

Python encapsulation is a process of wrapping up of data members and member functions within the class. In simple ways we can explain like not allowing a direct access to these variables and methods.

When there is a direct access the variables may be altered and default values can be replaced according to the scenario.

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) that refers to the idea of bundling data and methods that operate on that data within a single unit or object. The goal of encapsulation is to hide the internal details of an object’s implementation and to only expose a public interface or API that can be used to interact with the object.

In Python, encapsulation is achieved by using access modifiers to control the visibility of an object’s attributes and methods. There are two types of access modifiers in Python:

  1. Public: Public members are accessible from anywhere in the program. In Python, all attributes and methods are public by default.
  2. Private: Private members are only accessible within the class that defines them. In Python, you can create private members by prefixing the attribute or method name with two underscores (__). For example, __name would be a private attribute in a class.

Python Encapsulation is a way of encapsulating up of data members and member functions confused ?? go read this blog for a clarity now

Let us see the concept of encapsulation with a real time example and also go through this blog before getting started.

Python Encapsulation Video Tutorial :

In this video tutorial let us try to see the detailed implementation of encapsulation in python.

class A:
     a = 10
  
     def display(self):
         print(self.a)

a1 = A()

Here we have created a class and added variable and method and try to access them

print(a1.a)

output :

10

Now we can also alter the value of a variable as

a = 5

then when we try to print a we will be getting a = 5

So in order to maintain security we make us of encapsulation concept. Where we can try to make the variable private and access with the help of declared method as below

class A:
     __a = 10
  
     def display(self):
         print(self.a)

a1 = A()
a1.display()

output :

10

Now when you try to access variable directly rather than accessing through method you will get an error.

Encapsulation is a fundamental concept in object-oriented programming that is supported in Python through the use of access modifiers. In Python, all attributes and methods of a class are public by default, which means they can be accessed from anywhere in the program. However, you can create private attributes and methods by prefixing their names with two underscores (__).

Private attributes and methods in Python are not truly private, but rather their names are “mangled” by Python to avoid naming conflicts with other attributes and methods in subclasses. When you prefix an attribute or method name with two underscores, Python replaces the name with _classname__name, where classname is the name of the class in which the attribute or method is defined. This means that you can still access private attributes and methods from outside the class, but you need to use the mangled name.

If you have any query’s in this tutorial on Python Encapsulation do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates..

Go through the above specified video tutorial for further explanation.

Python Encapsulation

Python Access Modifiers : Public, Private, Protected

Python Access Modifiers

Python Access modifiers play a key role in programming the help us understand the usage restrictions on the variables or methods they are specified on.

Python does not have traditional access modifiers like public, private, or protected, as seen in other programming languages such as Java or C++. Instead, Python uses name mangling to indicate a private attribute, but this is not enforced by the language and is only a convention.

In Python, attributes and methods that are prefixed with a double underscore (__) are subject to name mangling. This means that their name is modified to include the class name as a prefix, in order to avoid naming conflicts between classes.

Access Modifiers specifies whether we have access of a specific class, variable. They are classified according to the requirement for each module.

public is accessible from outside the class, _protected is meant to be used within the class and its subclasses, and __private is inaccessible from outside the class.

Every modifier is different from each other

There are three kinds of python access modifiers

  • Public
  • Private
  • Protected

Python Access Modifiers Video Tutorial :

In this video tutorial let us try to see the detailed implementation of public, private and protected attributes in python.

Public :

Let’s try to observe the public access specifiers with the help of a example. This specifier is mostly used when you don’t want to provide any limitations on the class or variable declared.

Most of the variables are public if there is no security on access is a concern.

class A:
    a = 5

    def display(self):
        print('Hello World')

create an object for the class so that you can make use of the properties specified inside it.

a1 = A()
a1.display()

output :

Hello World

and now try to access variable

print(a1.A)

output:

5

Private :

Let’s us try to observe private implementation. These private methods and variables are only access within the class and not outside.

This provides a level of security such that not everyone can access the properties of a class. This will be helpful when dealing with the scenarios like online payment and so on..

You can specify a private attribute or method by prefixing it with a double underscore (__).

class A:
    __a = 5

    def display(self):
        print(self.__a)

create an object and call method

a1 = A()
a1.display()

output :

5

Protected :

Protected variables and methods are restricted to only defined class and derived classes so this is a difference between private and protected.

You can make use of this access modifier when you want to enable a level of protection.

You can indicate a protected attribute or method by prefixing it with a single underscore (_).

class A:
    _a = 5

    def _display(self):
        print(self._a)

Create a object and call display method as below.

a1 = A()
a1._display()

output :

5

Name mangling is only meant to prevent accidental name collisions between attributes of different classes. It does not provide true encapsulation or security, as the mangled name can still be accessed if desired. Therefore, it is generally considered good practice in Python to treat all attributes and methods as public, and rely on documentation and naming conventions to indicate their intended usage.


If you have any query’s in this tutorial on python access modifiers do let us know in the comment section below. If you like this tutorial do share us for more interesting updates.

Python Access Modifiers