Data hiding

#Public
class pdata:
    def __init__(self, d):
        self.data = d

    def show(self):
        print(self.data)

p = pdata(10)
p.show()
p.data = 20
p.show()
-----------------------------------
#PPrivate
class pdata:
    def __init__(self, d):
        self.__data = d

    def show(self):
        print(self.__data)

p = pdata(10)
p.show()
p.__data = 20
p.show()
-----------------------------------------
#Private
class pdata:
    def __init__(self, d):
        self.__data = d

    def show(self):
        print(self.__data)

p = pdata(10)
p.show()
p._pdata__data = 20 #name Managing
p.show()
------------------------------
Protected
class pdata:
    def __init__(self, d):
        self._data = d

    def show(self):
        print(self._data)

p = pdata(10)
p.show()
p.pdata_data = 20
p.show()

Data hiding in Python OOP is the concept of restricting access to the internal data of an object from outside the class. 🔐 It’s a way to prevent direct modification of data and protect the object’s integrity. This is typically achieved by using a naming convention that makes attributes “private” or “protected.”


🔒 How Data Hiding Works

Python doesn’t have true private keywords like some other languages (e.g., private in Java or C++). Instead, it relies on a convention and a mechanism called name mangling to achieve a similar effect.

  • Protected Members: By convention, a single leading underscore (_) is used for attributes that are “protected.” This signals to other developers that the attribute is intended for internal use and should not be accessed directly. For example: _protected_variable. While it can still be accessed and modified, it’s a strong hint to not do so.
  • Private Members: To make an attribute “private,” you use two leading underscores (__). This triggers name mangling, a process where Python automatically renames the attribute internally to prevent accidental access. For a class named MyClass and an attribute __private_variable, Python internally renames it to _MyClass__private_variable. This makes it difficult to access from outside the class, enforcing a form of data hiding.

📜 Example with Name Mangling

Here’s a simple program to illustrate the concept.

Python

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # This is a private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            print(f"Deposited {amount}. New balance is {self.__balance}")
        else:
            print("Invalid deposit amount.")

    def get_balance(self):
        return self.__balance

# Create an instance of BankAccount
my_account = BankAccount(100)

# This works because deposit is a public method
my_account.deposit(50)

# Trying to access the private attribute directly will result in an AttributeError
try:
    print(my_account.__balance)
except AttributeError as e:
    print(f"Error: {e}")

# This is how you can technically access it (but you shouldn't!)
print(my_account._BankAccount__balance)

In this example, the __balance attribute is hidden from direct external access. You must use the public deposit() or get_balance() methods to interact with it. This ensures that the balance is only modified through controlled logic, preventing invalid negative amounts from being set directly.

The try...except block demonstrates that trying to access __balance directly results in an AttributeError. The last print statement shows how name mangling works, but it’s a workaround that goes against the principle of data hiding and should be avoided in practice.

Similar Posts

  • List of Basic Regular Expression Patterns in Python

    Complete List of Basic Regular Expression Patterns in Python Character Classes Pattern Description Example [abc] Matches any one of the characters a, b, or c [aeiou] matches any vowel [^abc] Matches any character except a, b, or c [^0-9] matches non-digits [a-z] Matches any character in range a to z [a-z] matches lowercase letters [A-Z] Matches any character in range…

  • Escape Sequences in Python

    Escape Sequences in Python Escape sequences are special character combinations that represent other characters or actions in strings. Here’s a complete list of Python escape sequences with two examples for each: 1. \\ – Backslash python print(“This is a backslash: \\”) # Output: This is a backslash: \ print(“Path: C:\\Users\\Name”) # Output: Path: C:\Users\Name 2. \’ – Single quote…

  • Exception handling & Types of Errors in Python Programming

    Exception handling in Python is a process of responding to and managing errors that occur during a program’s execution, allowing the program to continue running without crashing. These errors, known as exceptions, disrupt the normal flow of the program and can be caught and dealt with using a try…except block. How It Works The core…

  • Functions as Objects

    Functions as Objects and First-Class Functions in Python In Python, functions are first-class objects, which means they can be: 1. Functions as Objects In Python, everything is an object, including functions. When you define a function, you’re creating a function object. python def greet(name): return f”Hello, {name}!” # The function is an object with type ‘function’…

  • Real-World Applications of Python Lists

    Python lists and their methods are used extensively in real-time applications across various domains. They are fundamental for organizing and manipulating ordered collections of data. Real-World Applications of Python Lists 1. Web Development In web development, lists are crucial for handling dynamic data. For example, a list can store user comments on a post, products…

  • pop(), remove(), clear(), and del 

    pop(), remove(), clear(), and del with 5 examples each, including slicing where applicable: 1. pop([index]) Removes and returns the item at the given index. If no index is given, it removes the last item. Examples: 2. remove(x) Removes the first occurrence of the specified value x. Raises ValueError if not found. Examples: 3. clear() Removes all elements from the list, making it empty. Examples: 4. del Statement Deletes elements by index or slice (not a method, but a…

Leave a Reply

Your email address will not be published. Required fields are marked *