Private Methods in Python: Do They Actually Exist?
Private Methods in Python - GeeksforGeeks
In Python, a private method is a method that is intended to be used only within the class where it is defined. These methods are not accessible from outside the class and are denoted by a single underscore (_) before the method name.
Here's an example of a class with a private method:
class MyClass:
def __init__(self):
self.public_var = "I'm a public variable!"
self._private_var = "I'm a private variable!"
def public_method(self):
print("This is a public method!")
self._private_method()
def _private_method(self):
print("This is a private method!")
As you can see, the _private_var
and _private_method
are intended to be used only inside the MyClass
. By convention, methods and variables that are intended to be private are named with a single underscore prefix.
Here's another example that demonstrates the use of private methods in a class hierarchy:
class MyBaseClass:
def __init__(self):
self.public_var = "I'm a public variable in MyBaseClass!"
self._private_var = "I'm a private variable in MyBaseClass!"
def public_method(self):
print("This is a public method in MyBaseClass!")
self._private_method()
def _private_method(self):
print("This is a private method in MyBaseClass!")
class MyDerivedClass(MyBaseClass):
def __init__(self):
super().__init__()
self.public_var = "I'm a public variable in MyDerivedClass!"
self._private_var = "I'm a private variable in MyDerivedClass!"
def public_method(self):
print("This is a public method in MyDerivedClass!")
self._private_method()
def _private_method(self):
print("This is a private method in MyDerivedClass!")
In this example, MyDerivedClass
inherits from MyBaseClass
, which has a private method and variable. MyDerivedClass
also has its own private method and variable. Both classes override the public_method
. When we create an instance of MyDerivedClass
, we can access the public methods and variables of both classes. However, the private methods and variables are still not accessible from outside the classes.
<aside> 🗒️ It's important to keep in mind that Python's private methods are just a convention and not a true access control mechanism. In fact, it's still possible to access private methods and variables from outside the class by using name mangling, although this is not recommended
</aside>