Wednesday 25 December 2013

public and private objects into python


Python does not support privacy directly . Programmer need to know when it is safe to modify attribute from outside but anyway with python you can achieve something like private with little tricks.
wow this is awesome .

Now let's see a person can put anything private to it or not :P
class Person(object):
  
    def __priva(self):
        print "I am Private"
   
    def publ(self):
        print " I am public"
   
    def callpriva(self):
        self.__priva()



Now When we will execute :
>>> p = Person()
>>> p.publ()
 I am public
>>> p.__priva()
Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    p.__priva()
AttributeError: 'Person' object has no attribute '__priva'

Explanation   : You can see  here we are not able to fetch that private method directly.

>>> p.callpriva()
I am Private
Explanation  : Here we can access private method inside class​


​Then how someone can access that variable  ???


You can do like :
>>>p._Person__priva
I am Private

​ wow ,  actually if python is getting any variable starting with  double underscore are “translated” by adding a single underscore and the class name to the beginning:

Note : If you do not want this name changing but you still want to send a signal for other  objects to stay away, you can use a single initial underscore names with an initial underscore aren’t imported with starred imports (from module import *)
Finally  : Python doesn’t really have an equivalent privacy support, although single
and double initial underscores do to some extent give you two levels of privacy

No comments:

Post a Comment