Private Methods in Python

  1. the Private Access Modifier in Python
  2. Declare a Private Method in Python

This tutorial demonstrates how to declare, manipulate, and utilize private methods in Python.

private is a keyword for a type of access modifier used in object-oriented programming languages. Access modifiers limit the visibility of a function or variable to a certain extent. Declaring your function/variable as private limits access only to the class encapsulating it.

A real-life comparison to a private method would be a home lighting system. The light switch and light bulb are like public methods because the person has direct access and visibility to them. At the same time, the electric wires inside the protective rubber are the private methods since they aren’t generally visible unless tampered with, but they still do their job without being attended to for the most part.

the Private Access Modifier in Python

In Python, private methods are methods that cannot be accessed outside the class that it is declared in nor to any other base class.

To declare a private method in Python, insert double underscores into the beginning of the method name.

the __init__() Method

A notable private method in Python is the __init__() method, which is used as a class constructor for a class object. This method is called when an object of a class is instantiated, depending on the method’s arguments.

For example, declare a class Person with two fields and an __init__() method:

class Person:
    name = ''
    age = 0
    
    def __init__(self, n, a):
        self.name = n
        self.age = a
    

Now, to access the private __init__() method outside of the class, we would need it to access it from the object of the class itself after instantiating it.

For example, in another file in the same directory, create an instance of the Person class and call the constructor using the class name.

sys.path.append(".")

from personClass import Person

person = Person("John Doe", 25)

print(person.name, person.age)

Output:

John Doe   25
Note

To import classes from another file into the current file, use sys.path.append() with the string path directory of the class you want to import as the argument. In this case, both files reside in the same folder, so a period . is sufficient. Afterward, import the class (Person) from the .py file (personClass.py).

The __init__() method can be called explicitly after instantiating the Person class into a variable to re-instantiate the object.

For example:

person = Person("John Doe", 25)
person.__init__("Jane Doe", 29)

print(person.name, person.age)

Output:

Jane Doe   29

Also, the __init()__ method can be explicitly called by calling it from the class itself. Although for this approach, you would need to explicitly put the first parameter self into the arguments.

person = Person("John Doe", 25)
Person.__init__(person, "Jack Sparrow", 46)   #person is the 'self' argument

print(person.name, person.age)

Output:

Jack Sparrow   46

All these approaches retain the private property of the __init__() method.

Now that this built-in method has been dissected. Let’s move on to actually implementing private methods of our own into a class and differentiating its access from a public method.

Declare a Private Method in Python

To declare a private method, prefix the method in question with double underscores __. Otherwise, it will be treated as a default public method.

Let’s extend the Person class from the previous example and create a subclass Employee that bases its constructor on the Person class.

Also, create two new methods within the person class, a public, and a private method.

class Person:
    name = ''
    age = 0
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def walk(self):
        print("Walking")
        
    def __call(self):
        print("Taking a call")

Now, create the derived class or subclass Employee that extends Person:

class Employee(Person):
    occupation = 'Unemployed'
    salary = 0
    
    def __init__(self, name, age, occupation, salary):
        Person.__init__(self, name, age)
        self.occupation = occupation
        self.salary = salary
        
    def work(self):
        print("Employee is working")
        self.walk()
        
    def takeCall(self):
        self.__call()
        print("Employee is taking a call")

Note

To extend a class to another class, add an argument to the class declaration which is the class name of the parent class. In this case, the argument is the Person class.

<div class="alert alert-warning" role="alert"><p>In this class, the <code>work()</code> and <code>takeCall()</code> methods externally call the <code>walk()</code> and <code>__call()</code> classes from the parent class <code>Person</code>, respectively.</p>

The other method externally calls a public method, and the other calls a private method from their parent class. Let’s see how this behavior works when we run it.

For example, given the class declarations above:

employee_1 = Employee("John Doe", 25, "Software Engineer", 40000)

employee_1.work()
employee_1.takeCall()

Output:

Employee is working
Walking
Traceback (most recent call last):
  File "python/demo.py", line 35, in <module>
    employee_1.takeCall()
  File "python/demo.py", line 29, in takeCall
    self.__call()
AttributeError: 'Employee' object has no attribute '_Employee__call'

The call to the work() method is successfully executed, printing out the statements from the work() and the walk() method. However, the call to takeCall() triggers an AttributeError because it does not recognize the __call() method from the Person class as a method of the Employee class. Extending a class to another class does not include its own private methods in the extension.

In summary, private methods in Python are declared by prefixing a method with two underscores, __. Declaring private methods allows a method to be exclusively reserved for the encapsulating class. A class extending another class with a private method will not inherit those methods and trigger an error if it tries to access it.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Class

  • Create Subclass From Superclass in Python
  • Nested Class in Python