Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
attribute
object oriented
access-modifiers

What are public, protected, & private access modifiers in Python?

Educative Answers Team

Most object-oriented programming languages, like C++ and Java, have access modifiers that can be used to restrict access to class members (i.e., variables and methods). Access modifiers are usually of three types: public, protected, and private.

Python, however, does not have any such access modifiers that guarantee control over access. In fact, all class variables and methods are publiccan be accessed outside the class.

Nonetheless, Python does have a convention to imitate access modification where you prefix variable/method names with underscores (_).

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

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 

Private access

You 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

You 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:

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

Try running the code with the last line uncommented print(p1.__height). You will notice it gives an AttributeError since you cannot access a private class member outside the class.

RELATED TAGS

python
attribute
object oriented
access-modifiers
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring