Monday, 25 September 2017

Access modifiers in Python

Access modifiers in Python :

In C++ and Java, things are pretty straight-forward. There are 3 magical and easy to remember access modifiers, that will do the job (public, protected and private). 

But there’s no such a thing in Python. That might be a little confusing at first, but it’s possible too.

Public:

All member variables and methods are public by default in Python. So when you want to make your member public, you just do nothing.

Protected:

Protected member is (in C++ and Java) accessible only from within the class and it’s sub classes.

How to accomplish this in Python? 

The answer is _ by convention. By prefixing the name of your member with a single underscore, you’re telling others “don’t touch this, unless you’re a subclass”.

  • This changes virtually nothing, you’ll still be able to access the variable from outside the class, only if you see something like this.
  • you explain politely to the person responsible for this, that the variable is protected and he should not access it or even worse, change it from outside the class.

Private:

By declaring your data member private you mean, that nobody should be able to access it from outside the class, i.e. strong you can’t touch this policy. 

Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into 

_<className>_ _<memberName>  ------> Name Mangling


Example:

class test:
    def  __init__(self): #constructor
        self.x=10  #public

        self._y=20  #protected

        self.__z=30  #private

    def  m1(self): #method
        print(self.x)
 
        print(self._y) 

        print(self.__z) 
    
t1=test( )

t1.m1( )

print(t1.x)

print(t1._y)

print(t1._test__z)

print(dir(t1))

Output:

10

20

30

10

20

30

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_test__z', '_y', 'm1', 'x']


No comments:

Post a Comment