Lesson Overview

Hello! In this lesson, we're revisiting Encapsulation, Private Attributes, and Private Methods in Object-Oriented Programming (OOP). Imagine encapsulation as an invisible fence safeguarding a garden from outside interference, keeping data and methods safe within. Within this garden, certain plants (Private Attributes and Methods) are only for the gardener's eyes. These are crucial for making your classes more robust and secure!

Into the Encapsulation

Encapsulation in OOP wraps up data and methods into a class. This organizational approach tidies the code and reinforces security. If you were to code a multiplayer game, for example, you could create a Player class, encapsulating data (health, armor, stamina) and methods (receive_damage, shield_hit, restore_health).

Now, player is an instance of the Player class on which you can call methods.

Private Attributes

Private Attributes, which can only be altered via class methods, limit outside interference. For instance, a BankAccount class might feature a balance private attribute that one could change only through deposits or withdrawals.

Here, __balance is private, thus ensuring the integrity of the account balance.

Private Methods

Like private attributes, private methods are accessible only within their class. Here's an example:

Here, add_yearly_interest is a public method that calls the private method __add_interest.

Remark the Privacy

In Python, a double underscore __ before the attribute or method name designates it as private.

Private attributes and methods are inaccessible directly from an instance. This arrangement helps maintain integrity.

Lesson Summary and Practice

Great job refreshing your understanding of encapsulation, private attributes, and private methods concepts in Python! Correctly understanding and applying these foundational principles of OOP make your code concise, robust, and secure.

Coming up next is hands-on practice. Keep up the good work – exciting exercises are just around the corner!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal