Access Modifiers in Python
Access Modifiers in Python
In most of the object-oriented languages, access modifiers are used to limit access to the variables and functions of a class. Access modifiers in Python are public, protected, private.
Python uses underscore symbol “_”, to define access modifiers for data members or methods.
Types of Modifiers:
- Public Access Modifier
- Protected Access Modifier
- Private Access Modifier
Public Access Modifier:
- The member of class which can be accessed by any part of that program.
- By default every member and method are Public.
Code #1 Public Access Modifier:
#python Program
#Rishikesh
# Access modifiers in Python
#public Access Modifier
class A(object):
def __init__(self, name , userid):
self.name = name
self.userid=userid
def display(self):
print(self.name)
ob = A(‘Rishikesh’ , ‘abc@.com’)
print(ob.userid)
ob.display()
Output:
abc@.com
Rishikesh
Protected Access Modifier :
- Variable or methods which are declared under protected class are only accessed by a class derived from it.
- single underscore “_” use to declare protected variables.
Code #2 Protected Access Modifier:
#python Program
#Rishikesh
# Access modifiers
#protected Access Modifier
class A(object):
_name=None
_userid=None
def __init__(self, name , userid):
self._name = name
self._userid=userid
def _display(self):
print(self._name)
class B(A):
def __init__(self,name,userid):
A.__init__(self,name,userid)
ob = B(‘Rishikesh’ , ‘abc@.com’)
print(ob._userid)
ob._display()
Output:
abc@.com
Rishikesh
Private Access Modifier :
- Variable or methods which are declared under private class are only accessed within the class
- single underscore “__” use to declare protected variables.
Code #2 Private Access Modifier:
#python Program
#Rishikesh
# Access modifiers
#private Access Modifier
class A(object):
#private member
__name=None
__userid=None
def __init__(self, name , userid):
self.__name = name
self.__userid=userid
def __display(self):
print(self.__name)
def dis(self):
self.__display()
class B(A):
def __init__(self,name,userid):
A.__init__(self,name,userid)
ob = B(‘PrepSter’ , ‘abc@.com’)
ob.dis()
#print(ob.__userid) #if u conmment both these it will raise an error
#ob.__display()
Output:
Prepster
Login/Signup to comment