You are on page 1of 12

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.

● Here, anywhere from the program means that the public


variables can be accessed from within the class as well as from
outside the class in which it is defined.
ACCESS SPECIFIERS

• Private variables , on the other hand, are those variables


that are defined in the class with a double score prefix
(__).

• These variables can be accessed only from within the class


and from nowhere outside the class.
ACCESS SPECIFIERS

We can access the private variable from anywhere outside


the class.

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

A private method can be accessed using the object


name as well as the class name from outside the
class.

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

we can make an instance variable or method private by using the double


underscore __, like:

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

We can still access the private members outside the class.

Python performs name mangling, so every member prefixed with


__ is changed to _class__member.

So, accessing name will then be p1._Person__name. However,


this is highly unadvised.
Example
To demonstrate each access modifier, we create a Person class
with three members: name (public), _age (protected), and
__height (private).

Next, we make an instance of Person and try accessing its


members:
ACCESS SPECIFIERS

class Person:
def __init__(self, name, age, height):
self.name = name # public
self._age = age # protected
self.__height = height # private

p1 = Person("John", 20, 170)

print(p1.name) # public: can be accessed


print(p1._age) # protected: can be accessed but not advised
# print(p1.__height) # private: will give AttributeError

You might also like