Thursday, 26 January 2017

ABSTRACTION OR DATA HIDING IN PYTHON

The concept of hiding the properties of one class from the other classes or other programs directly is known as data hiding or abstraction. (__ is prefix)

Example –
class A:
    __p=
100
   
def m1(self):
       
print 'in m1 of A'
A1=A()
A1.m1()
print A.p

Output –
Traceback (most recent call last):
  File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 7, in <module>
in m1 of A
    print A.p
AttributeError: class A has no attribute 'p'

Example –
class Counter:
    __secretcount=
0
   
def count(self):
       
self.__secretcount +=1
       
print self.__secretcount
C=Counter()
C.count()
C.count()
print C.__secretcount

Output –
Traceback (most recent call last):
1
  File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 9, in <module>
2
    print C.__secretcount
AttributeError: Counter instance has no attribute '__secretcount'

No comments:

Post a Comment