Access Modifier in Python. Topic – 45

Access Modifier in Python

Today in this post, we’re going to look at a very interesting topic, “Access Modifiers in Python.” But before that, let’s understand what an access modifier is. In programming languages, there are three ways to securely store data in variables. These three methods are called access modifiers. A Class in Python has three types of access modifiers:

  • Public Access Modifier
  • Protected Access Modifier
  • Private Access Modifier

But the interesting thing is that there are no access modifiers in Python. This is a myth. So now you might be wondering why you should read about it if there are no access modifiers. Let me explain what the situation is.

If we look at all other programming languages except Python, this concept exists. However, it doesn’t exist in Python. It’s a concept developed by programmers, but Python doesn’t officially acknowledge it. This means that in Python, data can be accessed publicly, but not directly in protected and private modes. However, they can be accessed indirectly. In all other programming languages, access is restricted. Let’s understand this through code.

Public Access Modifier:

Imagine constructing a house. Certain rooms, like the living room, are accessible to everyone visiting the house (different parts of your program). This is what the public access modifier does in Python. It makes class members (variables and methods) openly available to anyone using the class.

When you declare a class member as public (no special keyword is needed), you’re saying:

  • You can access this member using an object of the class (object_name.member_name).
  • You can access it even outside the class itself (from other parts of your program).
Python
class Employee:
    def __init__(self, name, age):
        self.name = name  # Public member
        self.age = age  # Public member

    def show_details(self):
        print(f"Name: {self.name}, Age: {self.age}")

# Create an Employee object
employee = Employee("Subham", 21)

# Access public members (name and show_details method) from the object
print(employee.name)  # Output: Subham
employee.show_details()  # Output: Name: Subham, Age: 21

 In this program, we can access any value from anywhere. So, this is the public access modifier.

Protected Access Modifier:

Python
class Employee:
    def __init__(self, name, age):
        self._name = name  # Private attribute (convention)
        self._age = age  # Private attribute (convention)

    def show_details(self):
        print(f"Name: {self._name}, Age: {self._age}")

    # Getter method to access private name attribute securely
    def get_name(self):
        return self._name


# Create an Employee object
employee = Employee("Subham", 21)

# Access public methods
employee.show_details()  # Output: Name: Subham, Age: 21

# Attempting to access private attributes directly will result in an error
# print(employee._name)  # AttributeError: 'Employee' object has no attribute '_name'

# Use the getter method to access the name securely
print(employee.get_name())  # Output: Subham

so break this programme step by step:

Private Attributes:

  • The _name and _age attributes are prefixed with a single underscore (_) to indicate they are intended for internal use within the class (convention).
  • This discourages direct access from outside the class.

Getter Method:

  • The get_name() method provides a controlled way to access the private _name attribute.
  • This promotes data encapsulation and can potentially add validation logic in the future (e.g., ensuring the name is not empty).

Accessing Details:

  • employee.show_details() displays both attributes using the public method.
  • Trying to access employee._name directly would result in an AttributeError.
  • employee.get_name() is used to retrieve the name securely.

Private Access Modifier

The members of a class that are declared private are accessible within the class only, private access modifier is the most secure access modifier. Data members of a class are declared private by adding a double underscore ‘__’ symbol before the data member of that class.

Python
# program to illustrate private access modifier in a class


class privet_class:
	
	# private members
	__name = None
	__roll = None
	__branch = None

	# constructor
	def __init__(self, name, roll, branch): 
		self.__name = name
		self.__roll = roll
		self.__branch = branch

	# private member function 
	def __displayDetails(self):
		
		# accessing private data members
		print("Name: ", self.__name)
		print("Roll: ", self.__roll)
		print("Branch: ", self.__branch)
	
	# public member function
	def accessPrivateFunction(self): 
			
		# accessing private member function
		self.__displayDetails() 

# creating object 
obj = privet_class("Ritwika", 17, "Cyber Security")

# calling public member function of the class
obj.accessPrivateFunction()

In the above program, __name, __roll and __branch are private members, __displayDetails() method is a private member function (these can only be accessed within the class) and accessPrivateFunction() method is a public member function of the class privet_class which can be accessed from anywhere within the program. The accessPrivateFunction() method accesses the private members of the class privet_class.

In object-oriented programming, classes often hold sensitive information. Private access modifiers act like a lock on a treasure chest, restricting direct access to these internal details while still allowing controlled interaction with them.

  • Marks a class member (variable or method) as accessible only from within the class itself.
  • This promotes encapsulation, data Protection
  • Unlike some other languages, Python doesn’t have a dedicated keyword for private access modifiers.
Inheritance in Python

Inheritance in Python

Inheritance in Python is one of the core concepts of Python. Inheritance is a powerful mechanism that allows you..

I hope you understand “Access Modifier in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog