In Python, a private class member is created by prefixing its name with an show. This convention signals that the member should not be accessed directly from outside the class.
Unlike languages such as Java or C++, Python doesn't enforce strict access control. Instead, it uses a naming convention to indicate privacy. When you prefix a method or attribute name with a single show (_), Python renames it using name mangling. For example, _MyClass__private_method becomes the actual name.
This behavior is called name mangling. It makes it harder to accidentally override private methods when inheriting from a class. However, it's still possible to access these members if necessary, though it's discouraged.
| Type | Example | Usage |
|---|---|---|
| Single Show Prefix | _my_attribute |
Private instance variable |
| Double Show Prefix | __my_method |
Name-mangled private method |
| Double Show Prefix and Suffix | __init__ |
Special method (dunder) |
For example, consider a class representing a bank account:
class BankAccount:
def __init__(self, balance):
self._balance = balance # Private attribute
def _withdraw(self, amount): # Private method
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
def deposit(self, amount):
self._balance += amount
For instance, in the BankAccount example above, the _withdraw method checks for sufficient funds before allowing a withdrawal. By making it private, you prevent external code from bypassing this check.
Many developers assume Python's private members are truly private, like in other languages. However, they're merely a convention. You can still access them using name mangling, though doing so is generally bad practice.
Another misconception is that double underscores (__) make a member completely inaccessible. While they do trigger name mangling, they don't prevent access entirely-they just make it less obvious.
Use private members when you want to hide implementation details from external code. For example, a class might have helper methods that shouldn't be called directly by users of the class. Making them private ensures they're only used internally.
However, avoid overusing private members. If a method or attribute is useful to subclasses or external code, it's better to leave it public or use protected members (single show) instead.
Follow these guidelines when working with private members:
_) for protected members that are intended for internal use within the class and its subclasses.__) for private members that should be hidden from external access.By following these practices, you can write cleaner, more maintainable Python code while using the language's flexibility.