-
Notifications
You must be signed in to change notification settings - Fork 1
Access Modifier in Python
Rajesh Khadka edited this page Nov 16, 2019
·
2 revisions
Python doesn't stops you to change the private and protected fields, by default all fields and methods are public. Implementation decision has been left for developers.
protected: _ (single underscore) before fields and methods
class User:
def __init__(self, username, password, gender):
self._username = username // i act like a protected but you can change me
def _login(self):
print('i am like a protected method but you can access me')
private: __ (double underscore) before fields and methods
class User:
def __init__(self, username, password, gender):
self.__username = username // i act like a protected but you can change me
self.__password = password // i act like a protected but you can change me
self.__gender = gender // i act like a protected but you can change me
def __login(self):
print('i like a private method but you can access me')
You can change private and protected fields and method as:
class Doctor:
def __init__(self,
name,
address,
specialities,
schedule,
degree):
self.name = name
self.address = address
self.specialities = specialities
self.schedule = schedule
self.__degree = degree
def __diagnose_patient(self):
print(F'diagnosed patient bob by doctor {self.name}')
doctor = Doctor('Dr. Bob', 'KTM', 'OPD', 'SUN: 7-8', 'MBBS')
doctor._Doctor__diagnose_patient(patient)
References: