Python Encapsulation, Encapsulation Abstraction

python encapsulation


Python Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). Python Encapsulation is the process of combining variables that store data and methods that work on those variables into a single unit called class. In Python Encapsulation, the variables are not accessed directly; it is accessed through the methods present in the class. Python Encapsulation ensures that the object’s internal representation (its state and behavior) are hidden from the rest of the application. Thus, python Encapsulation makes the concept of data hiding possible. In order to understand the concept of data hiding, imagine if some programmer is able to access the data stored in a variable from outside the class then there would be a very high danger of them writing their own (not encapsulated) code to deal with your data stored in a variable. This would, at the very least, lead to code duplication (i.e., useless efforts) and to inconsistencies if the implementations are not perfectly compatible. Instead, data hiding means that in order to access data stored in a variable everybody MUST use the methods that are provided, so that they are the same for everybody. An application using a class does not need to know its internal workings or how it is implemented. The program simply creates an object and uses it to invoke the methods of that class. Encapsulation Abstraction is a process where you show only “relevant” variables that are used to access data and “hide” implementation details of an object from the user. Consider your mobile phone you just need to know what buttons are to be pressed to send a message or make a call. What happens when you press a button, how your messages are sent, and how your calls are connected are all abstracted away from the user.

 Program to Demonstrate the Difference between Encapsulation Abstraction and Python Encapsulation

class foo:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
foo_object = foo(3,4)

In the above program, the internal representation of an object of foo class is hidden outside the class Encapsulation. Any accessible member (data/method) of an object of foo is restricted and can only be accessed by that object. Implementation of add() method is hidden → Abstraction. Encapsulation → Information Hiding Abstraction → Implementation Hiding.

Python Encapsulation Abstraction

Python Encapsulation example: Write Python Program to Find Whether it Lies in the First, Second, Third or Fourth Quadrant of x – y Plane using encapsulation Abstraction:

class Quadrant:
    def __init__(self, x, y):
        self.x_coord = x
        self.y_coord = y
    def determine_quadrant(self):
        if self.x_coord > 0 and self.y_coord > 0:
            print(f"Point with coordinates {(self.x_coord, self.y_coord)} lies in the FIRST Quadrant")
        elif self.x_coord < 0 and self.y_coord < 0:
            print(f"Point with coordinates {(self.x_coord, self.y_coord)} lies in the THIRD Quadrant")
        elif self.x_coord > 0 and self.y_coord < 0:
            print(f"Point with coordinates {(self.x_coord, self.y_coord)} lies in the FOURTH Quadrant")
        elif self.x_coord < 0 and self.y_coord > 0:
            print(f"Point with coordinates {(self.x_coord, self.y_coord)} lies in the SECOND Quadrant")
def main():
    point = Quadrant(-180, 180)
if __name__ == "__main__":

python encapsulation

Quadrant Depending on the value of x_coord and y_coord coordinates, the quadrant in which the point lies is determined. The following conditions characterize the four quadrants: in First Quadrant, both the x_coord and y_coord coordinates are positive; in Second Quadrant, the x_coord coordinate is negative, but the y_coord coordinate is positive; in Third Quadrantboth x_coord and y_coord   coordinates are negative; and in Fourth Quadrant, x_coord coordinate is positive but y_coord coordinate is negative . Use an if statement to determine which quadrant the point under consideration is in.

 Using Private Instance Variables and Methods

Instance variables or methods, which can be accessed within the same class and can’t be seen outside, are called private instance variables or private methods. Since there is a valid use-case for class-only private members (namely to avoid name clashes of names with names defined by subclasses), there is support for such a mechanism, which is called name mangling. In Python, an identifier prefixed with a double underscore (e.g., __spam) and with no trailing underscores should be treated as private (whether it is a method or an instance variable). Any identifier of the form __spam is textually replaced with _ classname__spam, where classname is the current class name with a leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class. Name mangling is helpful for letting subclasses override methods without breaking intraclass method calls. Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes. Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private.

Python Encapsulation example: Program to Demonstrate Private Instance Variables in Python

class PrivateDemo:
    def __init__(self):
        self.nonprivateinstance = "I'm not a private instance"
        self.__privateinstance = "I'm private instance"
    def display_privateinstance(self):
        print(f"{self.__privateinstance} used within the method of a class")
def main():
    demo = PrivateDemo()
    print("Invoke Method having private instance")
    print("Invoke non-private instance variable")
    print("Get attributes of the object")
    print("Trying to access private instance variable outside the class results in anerror")
if __name__ == "__main__":


Invoke Method having private instance
I'm private instance used within the method of a class
Invoke non-private instance variable
I'm not a private instance
Get attributes of the object
{'nonprivateinstance': "I'm not private instance", '_PrivateDemo__privateinstance': "I'm private instance"}
Trying to access private instance variable outside the class results in an error
AttributeError: 'PrivateDemo' object has no attribute '__privateinstance'

python encapsulation

In class PrivateDemo, the __privateinstance  variable cannot be invoked by an object outside the class but it can be used in a method defined within the class. If you try to access private instance variables outside the class, then it results in error – . You can use __dict__ to get all the attributes of an object – . As you can see in the output, the __ privateinstance variable is prefixed with _PrivateDemo.

Related Articles

Leave a Reply

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

Back to top button