Master Python Fundamentals: Encapsulation in User-Defined Classes
Photo by Pixabay: https://www.pexels.com/photo/turned-on-monitor-displaying-text-270623/

Master Python Fundamentals: Encapsulation in User-Defined Classes

Mastering the Python fundamentals is essential for anyone looking to become proficient in the language. Encapsulation is not just a fundamental concept in Python, but also one of the four pillars of object-oriented programming (OOP). The term encapsulation means "enclose in or as if in a capsule." This accurately reflects the concept of encapsulation in object-oriented programming, where data and the methods that operate on it are bundled together within a class, forming a protective "capsule." Think of encapsulation as putting your valuables into a safe. You only allow access to the contents through a key (in this case, specific methods), ensuring that your valuables (data) are protected. In this article, we are going to explore how we can achieve encapsulation in Python's user-defined classes.

Access Modifiers: Public, Protected and Private

In Python encapsulation isn’t as strict as in some other languages (like Java or C++), but it still offers the ability to control access to class attributes and methods using conventions. Python uses what we call access modifiers to control the visibility of attributes and methods within a class, allowing you to define which parts of your code can be accessed from outside the class. In Python, access modifiers can be categorized as public, protected, and private. Lets evaluate

  • Public: By default, when you define an attribute or method inside of the class, it can be accessed from anywhere within the program. Let's look at an example:

Here the name attribute is a public attribute. As a public attribute, we can access it from anywhere in the program. You can see that when we tried to access the name attribute using the person1 object (print(person1.name)), we got 'Moses', the value of the name attribute. We also accessed the name attribute via the display_name instance method. So a public attribute can be accessed or modified directly from outside the class or via a method.

  • Protected: We can also make an attribute or method protected by prepending it with a single underscore ( _ ). A protected attribute can also be accessed from within the class itself via a method and outside the classes. Let's modify the code from the previous example and make it protected:

Here we have changed the name attribute to be protected by prefixing it with a single underscore ( _ ). Notice that even though we have protected the attribute, we can still access it outside of the class (person1._name) and via the public method (display_name). So you can see that when you have a protected attribute, Python doesn’t restrict you from accessing it directly from outside the class. So what is the purpose of the protection? Making an attribute protected by prepending it with a single underscore simply sends a message to people that use the code (other developers) that this attribute is not intended to be accessed or modified outside the class or by external code. Its a warning that, "Hey, you can access this from outside the class, but you probably shouldn't!"

  • Private: The third level of protection that we can add to the attributes and methods of the class is private. We make an attribute private by prepending it with a double underscore ( __ ). Let's make our name attribute private:

In this version of the code, the name attribute has been changed to a private attribute by using a double underscore ( __ ). This modifies how the attribute is accessed. When we try to access it outside the class (person1.__name), the AttributeError occurs. Now, even though the __name attribute is now private and we cannot access it outside the class, we can still access it via the display_name public method. In this code, we still get 'The name of the person is Moses.' via the display_name() method. This is a key aspect of encapsulation: you’re restricting direct access to the data but still providing controlled access via methods.


Master Python Fundamentals (4 months left in 2024). Time to Act is Now.

This book is designed to help you master Python fundamentals the easy way. Video tutorials are coming soon. Master Python Fundamentals: The Ultimate Guide for Beginners:



Other Resources

Want t master data analysis with Python? Check out 50 Days of Data Analysis with Python: The Ultimate Challenge Book for Beginners

Challenge yourself with Python challenges. Check out 50 Days of Python: A Challenge a Day.

100 Python Tips and Tricks, Python Tips and Tricks: A Collection of 100 Basic & Intermediate Tips & Tricks.


Using Setters and Getters to Promote Encapsulation

The whole idea behind encapsulation is restricting direct access to an object’s internal data and providing controlled access through methods. In the previous section, we saw how prepending an attribute with a double underscore ( __ ) makes it private and not accessible from outside. Using getters and setters provides a structured way to retrieve and modify this private data. Let's modify the code using getters and setters:

  • The Getter: @property: In this code, we are now using @property decorator. This is the getter. This getter is allowing us to access the private attribute __name indirectly, and when we call person1.name, it returns a formatted string ('The name of the person is Moses'). How does this help with encapsulation? The getter method provides read-only access to the private data. Users of the class can read the value of __name but can’t modify it directly. The private attribute stays hidden from external access.
  • The Setter: @name.setter: The setter is created using the @name.setter decorator. Since the @property decorator provides us with read-only access to the private data, the @name.setter decorator allows us to change the value of the private attribute __name while validating or controlling the input. In this example, the setter validates the input to ensure it’s a string before assigning it to __name. If the input is invalid (e.g., a non-string), it returns an error message: Please enter a valid name. In this code, we have managed to change the '__name' attribute from Moses to Carol using the setter. How does this help with encapsulation? Well, the setter allows modification of the private attribute, but only in a controlled way. This prevents users from assigning invalid values, hence maintaining the integrity of the data.

You can see that by using setters and getters, we can ensure that the internal state of the objects of the class is only accessed and modified in a controlled, validated manner, which is the core benefit of encapsulation.

Conclusion

Encapsulation is an important concept in object-oriented programming, and mastering it in Python can significantly improve the structure, security, and maintainability of code. By using private attributes and providing controlled access through getters and setters, you can ensure that your data remains protected from unintended modifications while allowing the flexibility to evolve your codebase over time. Now that you’ve learned the power of encapsulation, you’re well on your way to mastering Python’s object-oriented capabilities.


Newsletter Sponsorship

You can reach a highly engaged audience of over 310,000 tech-savvy subscribers and grow your brand with a newsletter sponsorship. Contact me at [email protected] today to learn more about the sponsorship opportunities.


Jose Castillo

Estimating Department

4 周

Very informative!!

回复
Martin Hsu

Chief Architect | Senior Software Engineer | Data Integration

4 周

Very clean explanation on leveling up Python classes. Convention plays in important role in Python. Guido Van Rossum once said, 'we are all consenting adults'. I think the convention of a single underscore prefix is a good one to communicate this identifier is implementation specific, so don't depend on it. Instead, I recommend you use my class through my public interface. I think of it as a case of 'break glass in case of emergency' because while the class author doesn't intend for you to access it, you could.

回复
Hakeem Alimi

Maintenance Planner at Rom Oil Mills Ltd.

4 周

Thanks so much. I found it helpful

回复
Jeremiah Elochukwu

--DevOps Engineer | Cloud Solutions Architect | Site Reliability Engineer | AWS | kubernetes and Network Engineer

1 个月

very impresive

回复
Olamijuwon Victor

Junior Data Analysts || SQL || Excel || Data science || R programming language || Tableau || tech enthusiast ?? || Passionate about innovation, and Problem solving ||

1 个月

Am really blessed with this session of articule, about addressing a class, and about encapsulating a name directory

要查看或添加评论,请登录

社区洞察

其他会员也浏览了