Private variables and methods are the most restrictive members of a class. These members can only be accessed from within the class. There is no private
keyword in Python to make class members private.
When you prefix variables and methods with double underscore(__), then you make them private member of a class. And if you try to access private members from outside the class then you will get AttributeError
.
class Person: def __init__(self, firstName, lastName): self.__firstName = firstName self.__lastName = lastName def __display(self): print('My name is ', self.__firstName, self.__lastName) p = Person("Mitali", "Natani") print('First name: ', p.__firstName) print('Last name: ', p.__lastName) p.__display()
Output of the above program
AttributeError: 'Person' object has no attribute '__firstName'
If you are determined to access private members from outside the class then use this syntax- object._ClassName__variable
or object._ClassName__method
. But this is not recommended.
class Person: def __init__(self, firstName, lastName): self.__firstName = firstName self.__lastName = lastName def __display(self): print('My name is ', self.__firstName, self.__lastName) p = Person("Mitali", "Natani") print('First name: ', p._Person__firstName) print('Last name: ', p._Person__lastName) p._Person__display()
Output of the above program
First name: Mitali Last name: Natani My name is Mitai Natani