how to make class attribute private in python

Solutions on MaxInterview for how to make class attribute private in python by the best coders in the world

showing results for - "how to make class attribute private in python"
Laurel
10 Sep 2017
1# To make an attribute of a class private, use two underscores as the first two characters of the attribute name.
2
3class Student:
4    def __init__(self, name, id):
5        self.name = name
6        self.__id = id
7
8    def showInfo(self):
9        print(self.name)
10        print(self.__id)
11
12s = Student("Alice", 1234)
13
14# This will work, because name is a public attribute, __id is private and it is accessed from inside the class.
15s.showInfo()
16
17# This will work, because name is a public attribute
18print(s.name)
19
20# This will not work, because __id a private attribute of the class, so it cannot be accessed outside of the class.
21print(s.__id)
22