Python is an object-oriented programming language that provides the class and objects. A class may have different data types like methods. By default class methods are public where they can be called by using objects or instances. But some cases we may need to define a method as private to prevent access externally. We can make a class method as private by prefixing with the double underscore “__”.
Class Private Method
We can define a private method for a class by using the double underscore. Actually there is a default private method which is __init__()
. The __init__() method is a private method which is used as contructor when a new object is initialized. In the following example we create a function named display_name() which calls the private method __get_name() to get the name value.
class Person:
name="İsmail Baydan"
def display_name(self):
print(self.__get_name())
def __get_name(self):
return self.name
p = Person()
p.display_name()
İsmail Baydan
Calling Private Method
As stated previous private method can not be called outside of the scope like outside of the class. If we try to call the private method we get different errors like below. In the following example we call the private method _get_name()
.
class Person:
name="İsmail Baydan"
def display_name(self):
print(self.__get_name())
def __get_name(self):
return self.name
p = Person()
p.__get_name()
Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Person' object has no attribute '__get_name'