Auto AdSense

Saturday, 24 January 2015

Python Object Oriented - Data Hiding



  • #!/usr/bin/python

    class JustCounter:
       __secretCount = 0

       def count(self):
         self.__secretCount += 1
         print self.__secretCount

    counter = JustCounter()
    counter.count()
    counter.count()
    print counter.__secretCount
  • Output
    1
    2
    Traceback (most recent call last):
    File "test.py", line 12, in < module >
    print counter.__secretCount
    AttributeError: JustCounter instance has no attribute '__secretCount'
  • Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it would work for you:

    .........................
    print counter._JustCounter__secretCount
    Output
    1
    2
    2

No comments:

Post a Comment