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

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

  • Nested for loops, break, continue, and pass in for loops

    break, continue, and pass in for loops with simple examples. These statements allow you to control the flow of execution within a loop. 1. break Statement The break statement is used to terminate the loop entirely. When break is encountered, the loop immediately stops, and execution continues with the statement immediately following the loop. Example:…

  • Predefined Character Classes

    Predefined Character Classes Pattern Description Equivalent . Matches any character except newline \d Matches any digit [0-9] \D Matches any non-digit [^0-9] \w Matches any word character [a-zA-Z0-9_] \W Matches any non-word character [^a-zA-Z0-9_] \s Matches any whitespace character [ \t\n\r\f\v] \S Matches any non-whitespace character [^ \t\n\r\f\v] 1. Literal Character a Matches: The exact character…

  • 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…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

Leave a Reply

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