Python: Types of Access Modifiers
There are 3 types of access modifiers for a class in Python.
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.
Moving ahead to the type of access modifiers, they are:
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.

EXAMPLE:

class Demo:
x = 5
_y = 10
__z = 20
def met1(self):
print(Demo.x)
print(Demo._y)
print(Demo.__z)
s = Demo()
s.met1()
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
Post a Comment