Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

Private Methods in Python

Consider a simple class to denote restaurants:

class Restaurant:
 def __init__(self, name, address):
  self.name = name
  self.address = address

As you can see we can initialize a restaurant by providing a name and address. For instance, the following code creates one specific object of the class Restaurant.

r1 = Restaurant("Corner Cafe","123 Main Street")

Let us write a method in the Restaurant class to pretty print the name. The class definition now gets updated to:

class Restaurant:
 def __init__(self, name, address):
  self.name = name
  self.address = address

 def print(self):
  print("Restaurant " + self.name + " is located at " + self.address)

We can now do:

r1 = Restaurant("Corner Cafe","123 Main Street")
r1.print()

This will give the output:

Restaurant Corner Cafe is located at 123 Main Street

So far so good. Let us now create another method called “__print” (notice the double underscore) which also does printing but of a different kind:

class Restaurant:
 def __init__(self, name, address):
  self.name = name
  self.address = address

 def print(self):
  print("Restaurant " + self.name + " is located at " + self.address)

 def __print(self):
  print("Restaurant is a cool restaurant!")

Now, let us do:

r1 = Restaurant("Corner Cafe","123 Main Street")
r1.print()
r1.__print()

You will get this output:

Restaurant Corner Cafe is located at 123 Main Street
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    r1.__print()
AttributeError: 'Restaurant' object has no attribute '__print'

Note that the first method (print()) is properly invoked but the second method does not execute. In fact, you get an error saying that the Restaurant object has no attribute (or method) called “__print” (when in fact you know that it exists).

The reason we get this error is because the method is a private method and accessible only within the class, not outside the class (as you are attempting to do in your code). Here is an updated code:

class Restaurant:
 def __init__(self, name, address):
  self.name = name
  self.address = address

def print(self):
  print("Restaurant " + self.name + " is located at " + self.address)
  self.__print()

 def __print(self):
  print("Restaurant is a cool restaurant!")

r1 = Restaurant("Corner Cafe","123 Main Street")
r1.print()

Note that the “__print()” method is now being called from within the print() method. Also we removed the direct invocation of __print() in the main driver code. Let us run this; you will see this output:

Restaurant Corner Cafe is located at 123 Main Street
Restaurant is a cool restaurant!

You see that the private method now works and is accessible only within the class, not outside the class.

When do we use private methods?

Private Methods in Python

Private methods can be viewed as implementing “helper” functions. Think of them as auxiliary functions that will be used by the main, publicly visible methods but you do not want to make these methods accessible directly to the outside world.

For instance, you can create a method to output prices of foods on the restaurant menu (and this method can be public). But such a method might need to call a VAT method (Value Added Tax) which can be private and the internals of how much VAT tax is levied should not be directly accessible outside the Restaurant class.

You can think of similar applications in other classes.

“Cheating” with private methods

It turns out there is a way to “cheat” and call private methods. In the below code, note the last line:

class Restaurant:
 def __init__(self, name, address):
  self.name = name
  self.address = address

 def print(self):
  print("Restaurant " + self.name + " is located at " + self.address)

 def __print(self):
  print("Restaurant is a cool restaurant!")

r1 = Restaurant("Corner Cafe","123 Main Street")
r1.print()
r1._Restaurant__print()

In the last line, we have prefixed our call to “__print()” with the name of the class (and an underscore before it). This is called “name mangling” in Python. Think of it as a way to “test” your private methods before you truly make them private. This is very useful when you have multiple methods with overriding and with base class and inheritance class relationships (more on that in a different blogpost!)

Hope you enjoyed learning about private methods in Python.

If you are interested to learn more about Python object oriented programming features checkout our post about method overloading in Python.

Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.