← Go Back

How to Define a Private Method or Attribute

Python does not distinguish between public and private methods or attributes. Instead, all objects within a class or module can be accessed outside of them. However, there is a convention to prefix an underscore in order to indicate that an object should be interpreted (by programmers) as private.

class MyClass:

def __init__(self):
self._private_attribute = 1

def _private_method(self):
print("Hello world!")

my_object = MyClass()

In an API, for example, "private" functions are generally undocumented and do not follow any backward compatibility policy. For this reason, it is not advisable to use them outside the class or module in which they are defined.


🐍 You might also find interesting: