Access Specifiers
Access Specifiers
ACCESS SPECIFIERS
● Public variables are those that are defined in the class and can be
accessed from anywhere in the program, using the dot operator.
object._classname__privatevariable
***Not Recommended
Private Methods
• Like private attributes, we can even have primate methods
in our class.
• Usually , we keep those methods as private which have
implementation details.
• So like private attributes, we should also not use a private
method from anywhere outside the class.
Private Methods
object._classname__privatemethodname
***Not Recommended
ACCESS SPECIFIERS
Public access
By default, all members (instance variables and methods) are public:
class Person:
def __init__(self, name, age):
self.name = name # public
self.age = age # public
ACCESS SPECIFIERS
Protected access
To make an instance variable or method protected, the convention is to
prefix the name with a single underscore _, like:
class Person:
def __init__(self, name, age):
self._name = name # protected
self._age = age # protected
ACCESS SPECIFIERS
class Person:
def __init__(self, name, age):
self.__name = name # private
self.__age = age # private
The __name and __age instance variables cannot be accessed outside the
class, doing so will give an AttributeError:
p1 = Person("John", 20)
p1.__name # will give AttributeError
ACCESS SPECIFIERS
class Person:
def __init__(self, name, age, height):
self.name = name # public
self._age = age # protected
self.__height = height # private