add a private static method to a class in python

To add a private static method to a class in python, you can use the @staticmethod decorator along with the double underscore (__)

Here's a code snippet that demonstrates how to add a private static method to a class in python:

main.py
class MyClass:
    
    @staticmethod
    def __my_private_static_method():
        print("This is a private static method.")
        
    def my_public_method(self):
        print("This is a public method.")
        MyClass.__my_private_static_method()
254 chars
10 lines

In the above code, __my_private_static_method() is a private static method that can only be accessed within the class. The my_public_method() can be accessed outside the class.

To call the private static method from within the class, you need to use the class name followed by the double underscored method name: MyClass.__my_private_static_method().

Note that because __my_private_static_method() is a private method, attempting to call it from outside the class will result in a NameError.

gistlibby LogSnag