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:

Private Members:

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

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.