call a public static method on an instance of a class in python

In Python, you can call a public static method on an instance of a class by referencing the method through the class name instead of the instance name.

Here is an example:

main.py
class MyClass:
    @staticmethod
    def my_static_method():
        print("This is a static method!")

my_instance = MyClass()
MyClass.my_static_method()  # Calling the static method on the class
my_instance.my_static_method()  # Also calling the static method on the instance
278 chars
9 lines

In the example above, my_static_method is a public static method of MyClass. We can call this method on the class itself by using MyClass.my_static_method(). Additionally, we can also call it on an instance of the class by writing my_instance.my_static_method(), where my_instance is an instance of MyClass.

However, it's generally considered bad practice to call a static method on an instance, because a static method is meant to operate on class-level data, and not on instance-level data. Therefore, it's better to call the static method on the class directly.

gistlibby LogSnag