Hello Guys,
previously we learn about constructor and inheritance and basics of python.
Today we learn about encapsulation and polymorphism.
Encapsulation
Encapsulation is wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
To prevent accidental change, an object’s variable can only be changed by an object’s method. Those type of variables are known as private varibale.
Protected members
Protected members (in C++ and JAVA) are those members of the class which cannot be accessed outside the class but can be accessed from within the class and it’s subclasses.
Public, private and protected keyword
But
To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore “_”.
Code :
class
Base:
def
__init__(
self
):
self
._a
=
2
class
Derived(Base):
def
__init__(
self
):
Base.__init__(
self
)
print
(
"Calling protected member of base class: "
)
print
(
self
._a)
obj1
=
Base()
Output:
Calling protected member of base class:
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 “__”.
Code :
class
Base:
def
__init__(
self
):
self
.a
=
"GeeksforGeeks"
self
.__c
=
"GeeksforGeeks"
class
Derived(Base):
def
__init__(
self
):
Base.__init__(
self
)
print
(
"Calling private member of base class: "
)
print
(
self
.__a)
obj1
=
Base()
print
(obj1.a)
Output :
Polymorphism
The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types.
Code:
def
add(x, y, z
=
0
):
return
x
+
y
+
z
print
(add(
2
,
3
))
print
(add(
2
,
3
,
4
))
Output:
Watch this for method overriding Check here
❤❤Quarantine python group link ❤❤
8805271377 WhatsApp
Follow here ❤
@mr._mephisto_ Instagram
There will be no restrictions just feel free to learn.
Share and take one more step to share knowledge to others.
Believe in yourself 🤟 you are awesome.
Be safe, Be happy😁
Take care of yourself and your family
Of course watch movies and series🤟😉
And follow the guidelines of government
Comments
Post a Comment