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
Nonetheless, Python does have a convention to imitate access modification where you prefix variable/method names with underscores (_
).
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
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
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, accessingname
will then bep1._Person__name
. However, this is highly unadvised.
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 # publicself._age = age # protectedself.__height = height # privatep1 = Person("John", 20, 170)print(p1.name) # public: can be accessedprint(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.
Free Resources