Sample program
class Animal:
def __init__(self, Animalname):
self.__Animalname = Animalname
def name(self):
return self.__Animalname
x = Animal("This")
print x.name()
t = Animal("Pet2")
print t.__Animalname
class Animal:
def __init__(self, Animalname):
self.__Animalname = Animalname
def name(self):
return self.__Animalname
x = Animal("This")
print x.name()
t = Animal("Pet2")
print t.__Animalname
Output:
C:\Python27\python.exe E:/Scripts_to_learn/Scripts_to_learn/Encapsulation.py
This
Traceback (most recent call last):
File "E:/Scripts_to_learn/Scripts_to_learn/Encapsulation.py", line 17, in <module>
print t.__Animalname
AttributeError: Animal instance has no attribute '__Animalname'
Notes:
1. To make the attribute private, use "__". So that it can't be accessed from outside
2. To know/use the private attribute, create a method as above (Eg: Above 'name' method)
No comments:
Post a Comment