Access Modifiers in Python✌


ACCESS MODIFIERS 

        In most of the object-oriented languages access modifiers are used to limit the access to the variables and functions of a class



Types of Modifiers

Python uses ‘_’ symbol to determine the access control for a specific data member or a member function of a class. Access specifiers in Python have an important role to play in securing data from unauthorized access and in preventing it from being exploited. 

In python the representation of Public, Protected and Private access specifiers are as follows:

1. Public: eg:  name

2. Protected:  eg: _name

3. Private: eg: __name


These access modifiers define how the members of the class can be accessed. Of course, any member of a class is accessible inside any member function of that same class. 

Access Modifier: Public

The members declared as Public are accessible from outside the Class through an object of the class.

Access Modifier: Protected

The members declared as Protected are accessible from outside the class but only in a class derived from it that is in the child or subclass.

Access Modifier: Private

These members are only accessible from within the class. No outside Access is allowed.


ACCESS LIMIT OF SPECIFIERS


EXAMPLE:




class Demo:
  x = 5
  _y = 10
  __z = 20


  def m1(self):
    print(Demo.x)
    print(Demo._y)
    print(Demo.__z)


s = Demo()

s.m1()

5 10 20

print(Demo.x) #public variable
or print(s.x)

5

print(Demo._y) #protected variable
or print(s._y)

10

print(Demo.__z) #private variable
or print(s.__z)
---------------------------------------------------------------------------
AttributeError    
                        Traceback (most recent call last)
<ipython-input-131-bd3c01a1063d> in <module>()
----> 1 print(Demo.__z)

AttributeError:
 
type object 'Demo' has no attribute '__z'




To Access a Private Variable:


s._Demo__z #(objreference._classname__privatevariablename)

20

Comments