Private Methods and Attributes in a Python Class

Private methods and attributes are functions that can only be accessed from within a class. To define a private method or attribute, you simply add two underscores before its name.

__privatemethod

They're called "private" because they can't be accessed from outside the class.

Example

In this script, I’ll create a class with a private method.

The method name starts with two underscores: __

  1. class Example:
  2. def __privatemethod(self):
  3. print("hidden method")

Since this is a private method, it can’t be accessed from the rest of the program.

If you try to call it from an instance, the Python interpreter won’t find an attribute with that name and will return an error message.

>>> obj = Example()
>>> obj.__privatemethod()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
obj.__privatemethod()
AttributeError: 'Example' object has no attribute '__privatemethod'

But it does exist within the class.

To see it, you can use the dir function on the class name.

>>> dir(Example)
['_Example__privatemethod', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'method1', 'method2', 'method3', 'name']

The private method is indeed in the class, but it’s listed as _Example__privatemethod.

It doesn’t have the same name that I originally defined in the script, which was __privatemethod.

Note: The Python interpreter adds an underscore and the class name (_Example) as a prefix to obscure the method. The rest of the method name remains unchanged.

How to Access a Private Method

There’s a way to use a private method even outside the class.

If you create an instance and use the full name _Example__privatemethod, exactly as it appears in the class's dir output, the method will work correctly.

>>> obj = Example()
>>> obj._Example__privatemethod()
hidden method

This technique allows you to access private methods and attributes from outside the class.

And that's how it's done.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Classes