Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the practice of bundling data (attributes) and the methods that operate on the data (behaviors) within a single unit, which is called a class. Encapsulation provides a way to restrict direct access to an object's internal state and only expose a well-defined interface.
In this tutorial, we'll demonstrate how to apply encapsulation in Python using private attributes and accessor methods (getters and setters).
Example: Applying Encapsulation
Let's create a class called Person
that encapsulates the name
and age
attributes:
class Person: def __init__(self, name, age): self.__name = name self.__age = age # Getter for name def get_name(self): return self.__name # Setter for name def set_name(self, name): self.__name = name # Getter for age def get_age(self): return self.__age # Setter for age def set_age(self, age): if 0 <= age <= 120: self.__age = age else: raise ValueError("Invalid age") def introduce(self): print(f"Hello, my name is {self.__name} and I am {self.__age} years old.")
In this example, we define the Person
class with the following components:
__name
and __age
attributes are marked as private by using a double underscore prefix. This makes them inaccessible from outside the class.get_name()
and get_age()
methods are the getters for the name
and age
attributes, respectively. They allow you to access the private attributes without directly accessing them.set_name()
and set_age()
methods are the setters for the name
and age
attributes, respectively. They allow you to modify the private attributes while enforcing any necessary validation rules. In this case, the set_age()
method checks if the age is within a valid range before setting it.introduce()
method is a public method that prints a message introducing the person.Example: Using the Encapsulated Class
Let's create instances of the Person
class and demonstrate the encapsulation:
# Create an instance of the Person class person1 = Person("Alice", 30) # Access the name and age using the getters print(person1.get_name()) # Output: Alice print(person1.get_age()) # Output: 30 # Modify the name and age using the setters person1.set_name("Alicia") person1.set_age(31) # Call the introduce() method person1.introduce() # Output: Hello, my name is Alicia and I am 31 years old. # Try to access the private attributes directly (will raise an AttributeError) try: print(person1.__name) except AttributeError as e: print(e) # Output: 'Person' object has no attribute '__name'
In this example, we create an instance of the Person
class and use the getter and setter methods to access and modify the private attributes. We also demonstrate that trying to access the private attributes directly raises an AttributeError
.
In conclusion, encapsulation in Python allows you to bundle data and behaviors within a class and restrict direct access to an object's internal state. By applying encapsulation, you can create more maintainable, flexible, and robust classes.
Private and public members in Python encapsulation:
_
) is used to indicate "protected" attributes, and a double leading underscore (__
) indicates "private" attributes.class MyClass: def __init__(self): self.public_attribute = "I am public" self._protected_attribute = "I am protected" self.__private_attribute = "I am private"
Using underscores for data hiding in Python:
class MyClass: def __init__(self): self._protected_attribute = "I am protected" self.__private_attribute = "I am private"
Protecting attributes and methods in Python classes:
class MyClass: def __init__(self): self._protected_attribute = "I am protected" self.__private_attribute = "I am private" def _protected_method(self): print("I am a protected method") def __private_method(self): print("I am a private method")