add a private method to a class in python

To add a private method to a class in Python, you can use a prefix underscore (_) to indicate that the method is intended to be used only within the class and should not be accessed outside of it. Here's an example:

main.py
class MyClass:
    def __init__(self):
        self.public_variable = "I'm a public variable"
        self._private_variable = "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")
336 chars
12 lines

In the example above, we have defined two methods, public_method and _private_method. The public_method is a regular method that can be accessed from outside of the class, but it calls the _private_method, which is marked as private using a single underscore prefix. This means that _private_method should not be called outside of the class.

To create an instance of MyClass, you can do the following:

main.py
my_object = MyClass()
22 chars
2 lines

And then you can call the public method, which will in turn call the private method:

main.py
my_object.public_method()
# Output:
# This is a public method
# This is a private method
89 chars
5 lines

Note that the use of the single underscore by convention indicates that the method should not be accessed outside of the class, but it doesn't enforce it. You can still access the method from outside of the class if you really want to, although it's not recommended.

gistlibby LogSnag