Public and Private Members in Python
In Python, the accessibility of class members (attributes and methods) can be controlled through public and private members. This encapsulation helps maintain the integrity of the data and hides the internal workings of the class.
Public Members:
- Definition: Public members are accessible from outside the class. They are the default visibility for class attributes and methods.
- Usage: They are used when you want to expose the members to be accessed directly by objects of the class.
- Syntax: Public members do not require any special prefix.
Private Members:
- Definition: Private members are not accessible from outside the class. They are intended for internal use only.
- Usage: They are used to hide the implementation details and protect the data from unauthorized access or modification.
- Syntax: Private members are defined by prefixing the member name with two underscores (e.g.,
__private_member
).
Example of Public and Private Members
This example demonstrates the use of public and private members in a Python class.
Code Example
class Person:
def __init__(self, name, age):
self.name = name # Public member
self.__age = age # Private member
def display_info(self):
print("Name:", self.name)
print("Age:", self.__age) # Accessing private member within the class
# Creating an object of the class
person = Person("Alice", 30)
# Accessing public member
print("Public Member (Name):", person.name)
# Accessing private member directly will raise an AttributeError
try:
print("Private Member (Age):", person.__age)
except AttributeError as e:
print(e)
# Accessing private member through a method
person.display_info()
Output
Public Member (Name): Alice
'Person' object has no attribute '__age'
Name: Alice
Age: 30
'Person' object has no attribute '__age'
Name: Alice
Age: 30
Conclusion
Understanding public and private members is crucial for implementing encapsulation in Python. Public members allow easy access and interaction with the object, while private members help protect the integrity of the data by restricting access from outside the class.