How Many Types Of Access Modifiers Are There In Python-
-
1) Public
-
2) Private
-
3) Protected
1) Private-
– ‘__’ can be used to create private variable and method. – Private variable and methods can be accessed within the class.
class Emp:
name = 'Rohit' # public variable
__salary = 17000 # Private variable because it has a syntax "__"
def main():
print(Emp.name)
print(Emp.__salary)
Emp.main()
Output-
Rohit
17000
- Qsn- Can we call the private methods of another class?
- Answer-Yes, We can call private methods of another class by calling the public method of that class.
Ex-
class Test:
def a1(self):
print("a1")
def __a2(self):
print("a2")
def a3(self):
self.__a2()
class TestMain:
def main():
obj = Test()
obj.a1()
#obj.__a2() --> Error AttributeError: 'Test' object has no attribute '_TestMain__a2'
obj.a3()
TestMain.main()
Output-
a1
a2
2) Protected-
(If you are new in Python. I will recommend to learn this concept after Inheritance) – ‘_’ is used to create protected variables and methods. – Another class variables and methods can be accessed by using protected Access Modifiers In Python only if we have the parent-child relationship even in modules also.
Ex-
a=10 #public _a=10 #Protected __a=10 #Private
Ex-
class Parent:
def __init__(self, a, b):
self._a = a
self._b = b
def display(self):
print("a is-", self._a)
print("b is-", self._b)
class Child(Parent):
def __init__(self, a, b):
Parent.__init__(self, a, b)
def sum(self):
c = self._a + self._b
print("sum is-", c)
obj = Child(4, 3)
obj.display()
obj.sum()
Output-
a is- 4
b is- 3
sum is- 7

