In this tutorial, we will learn how to create private methods in Python classes, a valuable concept that enhances security and prevents unauthorized access to class methods.
Unlike other object-oriented programming languages, Python does not contain a built-in private keyword. Instead, we need a unique workaround to create private methods in Python.
Step 1: Understanding the Concept of Private Methods
In Python, a method can be made private by prefixing the method name with a double underscore ‘__’. A private method cannot be called on the object outside the class. It can only be accessed within a class.
Step 2: Defining the class and Private Method
The following is the Python syntax for creating private methods in a class:
1 2 3 |
class ClassName: def __private_method(self): pass |
Step 3: Accessing a Private Method
To access a private method, we have to define another method that calls this private method internally, like so:
1 2 3 4 5 6 7 |
class ClassName: def __private_method(self): # This is a private method def public_method(self): # This method calls the private method self.__private_method() |
You can call this method with the object of ClassName because it’s public.
Step 4: Handle Errors
Remember, private means it cannot be accessed directly outside the class. If you try to do so, you will get an error:
1 2 3 4 5 |
# Creating an object for the class object = ClassName() # Trying to call the private method object.__private_method() |
This will output the error:
AttributeError: 'ClassName' object has no attribute '__private_method'
Step 5: Correct Way to Call Private Method
The correct way to call a private method is to call it through a public method:
1 2 |
# Correct way to call private method object.public_method() |
Full Python Code:
Here is the full Python code as mentioned in the tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 |
class ClassName: def __private_method(self): print("This is a private method") def public_method(self): self.__private_method() # Instantiate the class object = ClassName() # Call the private method via a public method object.public_method() |
This is a private method
Conclusion
In Python, creating private methods can enhance the security of your code, but remember: you cannot call these methods directly. Use a companion public method instead.
By following the steps mentioned in this tutorial, you can effectively create and use private methods in Python classes.