Accessing private variables from another class:
- One class cannot access the private information from another class directly.
- A class(object) is allowed to share(send or receive) the private data in communication.
- Communication between objects is possible using methods.
- Two standard methods get() and set() to share the information.
class First:
__a = 10
def getA():
return First.__a
class Second:
def main():
# print("a val : ", First.__a)
print("a val : ", First.getA())
return
Second.main()
Accessing dynamic private variable using dynamic get() method:
class First:
def __init__(self,a):
self.__a = a
return
def getA(self):
return self.__a
class Second:
def main():
obj = First(10)
# print("a val : ", obj.__a)
print("a val : ", obj.getA())
return
Second.main()
Modifying private variables data:
- We cannot set values directly to private variables.
- We use set() method to modify the data.
Note: When we try set the value directly to private variable, the value will be omitted.
class First:
__a=10
def getA():
return First.__a
def setA(a):
First.__a = a
return
class Second:
def main():
print("a val :", First.getA())
First.__a=20
print("a val :", First.getA())
First.setA(20)
print("a val :", First.getA())
return
Second.main()
Setting values to dynamic private variables:
class First:
def __init__(self,a):
self.__a = a
return
def getA(self):
return self.__a
def setA(self,a):
self.__a = a
return
class Second:
def main():
obj = First(10)
print("a val :", obj.getA())
obj.setA(20)
print("a val :", obj.getA())
return
Second.main()