Friday, May 19, 2023

#PYTHON(DAY24)ENCAPSULATION

 

#PYTHON(DAY24)

Encapsulation

Encapsulation is one of the most fundamental concepts in object-oriented programming (OOP). This is the concept of wrapping data and methods that work with data in one unit. This prevents data modification accidentally by limiting access to variables and methods. An object’s method can change a variable’s value to prevent accidental changes. These variables are called private variables.

encapsulation

Protected Members

Protected members in C++ and Java are members of a class that can only be accessed within the class but cannot be accessed by anyone outside it. This can be done in Python by following the convention and prefixing the name with a single underscore.

The protected variable can be accessed from the class and in the derived classes (it can also be modified in the derived classes), but it is customary to not access it out of the class body.

The __init__ method, which is a constructor, runs when an object of a type is instantiated.

Example:

# Creating a base class
class Base:
def __init__(self):

# Protected member
self._a = 2

# Creating a derived class
class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)

# Modify the protected variable:
self._a = 3
print("Calling modified protected member outside class: ",
self._a)


obj1 = Derived()

obj2 = Base()

# Calling protected member
# Can be accessed but should not be done due to convention
print("Accessing protected member of obj1: ", obj1._a)

# Accessing the protected variable outside
print("Accessing protected member of obj2: ", obj2._a)

And the output is:

Calling protected member of base class:  2
Calling modified protected member outside class: 3
Accessing protected member of obj1: 3
Accessing protected member of obj2: 2

Private members

Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside a class.

However, to define a private member prefix the member name with double underscore “__”.

class Base1:  
def __init__(self):
self.p = "Javatpoint"
self.__q = "Javatpoint"

# Creating a derived class
class Derived1(Base1):
def __init__(self):

# Calling constructor of
# Base class
Base1.__init__(self)
print("We will call the private member of base class: ")
print(self.__q)


# Driver code
obj_1 = Base1()
print(obj_1.p)

And the output is:

Javatpoint

No comments:

Post a Comment

Building Static Website(part6) HTML Lists

  Building Static Website (part6) HTML Lists Today, let us add some lists to our detailed view section by using html lists. Lists: List is a...