Access Modifiers in Python
Access Modifiers are employed by numerous programming languages, including C++, Java, and Python, which adhere to the object-oriented programming paradigm. These modifiers serve to regulate the accessibility of class member variables and methods from outside the defined class. Encapsulation, a fundamental concept in OOP, safeguards the internal data of a class by utilizing access modifiers like Public, Protected, and Private.
In this tutorial, we will explore Access Modifiers along with their various types. Additionally, we will examine how to implement them in the Python programming language.
Types of Access Modifiers
Python offers three levels of access modifiers:
- Public (name): The members of the public access modifier can be accessed anywhere.
- Protected (_name): The members of the protected access modifier should be accessed only within the class and its subclasses. It is not intended for public use.
- Private (__name): The members of the private access modifier can be accessed only within the class (using name mangling).
Let’s explore these modifiers through a series of examples.
1. Public Access Modifier
The member variables and functions associated with the public access modifier can be accessed from any location within the program. In Python, all attributes and methods within classes are public by default, unless they are specifically altered.
Public Access Modifier Example
Let's examine the subsequent illustration of the public access modifier:
Example
# defining a class 'Animal'
class Animal:
def __init__(self, name, home):
self.name = name # public attribute
self.home = home # public attribute
# public method
def display_data(self):
print(self.name, "lives in", self.home)
# instantiating the class
wild_animal = Animal("Lion", "Den")
# printing the values of the public attributes
print(wild_animal.name)
print(wild_animal.home)
# calling the method to print details
wild_animal.display_data()
Output:
Lion
Den
Lion lives in Den
Explanation:
In the code excerpt above, a class named Animal is established. This Animal class contains two member variables: name and home, along with a method called displaydata that outputs the values of these member variables. Both of these variables are accessible publicly since no specific access modifier (or naming convention) has been designated for them. Subsequently, we created an instance of the class referred to as wildanimal. We then proceeded to display the values of the public attributes and invoked the method to output the information regarding the instantiated object.
Key Features of Public Access Modifier
The Public Access Modifier in Python encompasses several important characteristics, including the following:
- Entities in the public domain have the ability to access the public access modifier from any location.
- Attributes and methods alike can be altered from outside the class.
2. Protected Access Modifier
The member variables and methods defined with the protected access modifier can only be accessed within the class in which they are declared, as well as in any subclasses that extend that class. To establish a protected field or method, developers typically adhere to a specific naming convention, often involving the addition of a prefix to the name of the variable or function.
In Python, protected members are denoted by a single underscore preceding the variable name (_variable). It is essential to understand that the Python interpreter does not impose this limitation in the same way that other programming languages do; rather, it serves as a guideline for developers. Programmers might attempt to access these members using their straightforward names instead of utilizing the appropriate prefix.
Protected Access Modifier Example
Let us examine the subsequent illustration of a protected access modifier.
Example
# defining a class named Animal
class Animal:
def __init__(self, name, home):
self._name = name # protected attribute
self._home = home # protected attribute
# protected method
def _display_data(self):
print(self._name, "lives in", self._home)
# instantiating the class
wild_animal = Animal("Lion", "Den")
# printing the values of the protected attributes
# Note: Accessing protected members is possible, but it's discouraged
print(wild_animal._name)
print(wild_animal._home)
# calling the protected method
wild_animal._display_data()
Output:
Lion
Den
Lion lives in Den
Explanation:
In the preceding code segment, we created a class named Animal. This Animal class contains two member variables, name and home, along with a protected method called displaydata which outputs the values of these member variables. Both of these attributes are designated as protected, indicated by a leading underscore () in their names. Subsequently, we instantiated the class as wildanimal. Following this, we printed the values of the protected attributes and invoked the method to display the information of the instantiated object.
Note: It is possible to access the protected members; however, it is discouraged.
Key Features of Protected Access Modifier
- Single underscore (_) is just a convention. It does not prevent access from outside.
- The variable can still be accessed and modified from outside the class.
- Protected members are often used when designing parent-child class relationships (inheritance), where they can be accessed in a subclass.
3. Private Access Modifier
The variables and methods that utilize the private access modifier can solely be accessed from within the class itself. This access modifier is regarded as the most secure among the various options available. Members declared as private are marked with double underscores (__) preceding the name of the variable or method. Python employs a technique known as name mangling, which alters the internal name of the variable to safeguard against unintentional access.
Private Access Modifier Example
Let us examine the subsequent example that illustrates the private access modifier.
Example
# defining a class 'Animal'
class Animal:
def __init__(self, name, home):
self.__name = name # private attribute
self.__home = home # private attribute
# private method
def __display_data(self):
print(self.__name, "lives in", self.__home)
# instantiating the class
wild_animal = Animal("Lion", "Den")
# trying to access private attributes directly (this will raise an AttributeError)
# print(wild_animal.__name) # This will cause an error
# print(wild_animal.__home) # This will cause an error
# trying to call the private method directly (this will also raise an AttributeError)
# wild_animal.__display_data() # This will also cause an error
Explanation:
In the code snippet provided above, we have established a class referred to as Animal. This Animal class comprises two member variables, name and home, alongside a private method _displaydata that outputs the values of the member variables. Both variables are designated as protected, indicated by the use of a double underscore (_) at the beginning of their names. Following this, we created an instance of the class named wildanimal. We then attempted to output the values of the private attributes and invoked the method to display the details of the instantiated object. However, executing this will result in an error.
Accessing Private Members using Name Mangling
In Python, private attributes cannot be accessed or altered directly from outside the class. Python employs Name Mangling, which complicates this process, although it is not entirely unfeasible. However, it is highly advised against attempting this, as it undermines the principle of encapsulation.
Name mangling allows us to alter the names of a class's private members from _name to ClassName__name. To demonstrate this concept, we will examine the following example that showcases how name mangling is employed to access the private members within a class.
Example
# defining a class named Animal
class Animal:
def __init__(self, name, home):
self.__name = name # private attribute
self.__home = home # private attribute
# private method
def __display_data(self):
print(self.__name, "lives in", self.__home)
# instantiating the class
wild_animal = Animal("Lion", "Den")
# accessing private attributes using Name Mangling
print(wild_animal._Animal__name)
print(wild_animal._Animal__home)
# trying to call the private method using Name Mangling
wild_animal._Animal__display_data()
Output:
Lion
Den
Lion lives in Den
Explanation:
In the preceding code example, a class named Animal has been established. This Animal class includes two member variables, name and home, along with a private method named _displaydata that outputs the values of these member variables. Both member variables are designated as protected, indicated by the use of a double underscore (_) as a prefix. Subsequently, we created an instance of the class referred to as wildanimal.
Subsequently, we applied name mangling, altering the private attributes from name and home to Animalname and Animal__home, correspondingly, and displayed their values for the users. We invoked the method once more, utilizing name mangling to output the specifics of the instantiated object. In this instance, the values were printed without any issues.
Key Features of Private Access Modifier
- The members of the Private access modifier cannot be accessed directly from outside the class.
- Name mangling grants users access to private members; however, it should be avoided unless necessary.
- This ensures better encapsulation and prevents accidental modification of variables.
Comparison between the Different Access Modifiers in Python
Next, we will examine a comparative table that highlights the differences among public, protected, and private access modifiers in Python.
| Access Modifier | Syntax | Accessibility | Example | Key Features |
|---|---|---|---|---|
| Public | varName | Public members are accessible from anywhere (inside and outside the class) | self.varName | Default access modifier in Python.No restrictions on accessing or modifying the public attributes and methods. |
| Protected | _varName | Protected members are accessible within the class and subclass (It does not enforce this restriction; it simply provides a convention) | self._varName | Indicated using a single underscore (_).Attributes and methods can be accessed from outside the class; however, they should be treated as internal. |
| Private | __varName | Private members are accessible only within the class (We can also apply name mangling to access the members) | self.__varName | Indicated using double underscores (_).We cannot access the private members directly from outside the class.Attributes and methods can be accessed using name mangling. (For example, ClassName__varName) |
- Default access modifier in Python.
- No restrictions on accessing or modifying the public attributes and methods.
- Indicated using a single underscore (_).
- Attributes and methods can be accessed from outside the class; however, they should be treated as internal.
- Indicated using double underscores (__).
- We cannot access the private members directly from outside the class.
- Attributes and methods can be accessed using name mangling. (For example, ClassName_varName)
Conclusion
In the preceding tutorial, we explored the foundational concepts of Object-Oriented Programming (OOP). Additionally, we examined the various principles that underpin OOP. Following that, we delved deeply into the notion of encapsulation. We discovered that encapsulation, which is a core tenet of OOP, plays a crucial role in safeguarding data while facilitating regulated access to the class's attributes and methods. Python provides three distinct access modifiers to enforce encapsulation within programs. These access modifiers—public, protected, and private—enable developers to control data visibility and enhance security.
Access Modifiers in Python FAQs
1. What are access modifiers in Python?
Access Modifiers serve the purpose of altering the accessibility of the member variables and methods within a class from external sources.
2. Which access modifiers does Python support?
Python offers three levels of access modifiers:
- Public (name): The members of the public access modifier can be accessed anywhere.
- Protected (_name): The members of the protected access modifier should be accessed only within the class and its subclasses. It is not intended for public use.
- Private (__name): The members of the private access modifier can be accessed only within the class (using name mangling).
3. What is a protected member in Python?
In Python, protected members are represented by a single underscore prefix (_variable). Unlike many other programming languages, the Python interpreter does not strictly enforce this convention; it serves primarily as a guideline for developers. Programmers may still attempt to access these members using their straightforward names rather than utilizing the appropriate prefix.
4. What is a private member in Python?
Private attributes are denoted by a double underscore (__variable). They cannot be accessed directly from outside the class.
5. Can private variables be accessed outside the class?
Indeed, this is possible solely through name mangling (ClassName_variable). However, this practice is generally discouraged because private attributes are intended for use exclusively within the class itself.