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.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFDyZ-x_UcjxCH0Jj5ItnMf6DnHQwjb8bqG265XdBsvBqnqsW25Qaw9rotODNW5hO2VwStIVJVGBxP3JGzOVDMrtT5HWQG5STUFUSMTxlJewjMkmWAAc8ylsKfl7MhZQ64tZR8DAkr-lFq/w416-h209/image.png)
EXAMPLE:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAWmYNLD3K7vm80Mozh5AbA5KUkNng5pO3zttYSbQK5fUMIJXO8WZ2OHWut9ypUvBj9E5JDphSHn38lo9vsMOpTVYRb03WR7bARAqC70_1ke3L6CwlDHJr0Vj2I-gJtELLqNSeSDqk8EjM/w495-h196/image.png)
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