Static Method / Class Method example in Python


Methods is sub-routine that associated with class. Usually, we can using the method inside a class from the instance objects. Static method / Class method is refering to accessing method using Class explicitly. That means to using method inside class, we’re using Class.. Let see the example of Class method in Python:

1
2
3
4
5
6
class Hello:
    def result(self, name):
        print("Hello " + name)

if __name__ == "__main__":
    Hello.result("", "Yodi")


So, at this example, we try to execute method directly on the Class. And it will give us results:

1
2
3
4
5
Traceback (most recent call last):
  File "/python-collection/basic/static_method_class.py", line 6, in <module>
    Hello.result("", "Yodi")
TypeError: unbound method result() must be called with Hello instance as first argument (got str instance instead)
[Finished in 0.6s]

Yes, this unbound method should be called from the instance instead of Class. But, don’t worry, we can use another alternative by using Callable:

1
2
3
4
5
6
7
8
9
10
11
12
class Callable:
    def __init__(self, anycallable):
        self.__call__ = anycallable

class Hello:
    def result(self, name):
        print("Hello " + name)

    result = Callable(result)

if __name__ == "__main__":
    Hello.result("", "Yodi")

When we execute this, it will give result:

1
Hello Yodi

I will explain more about “__call__” in this example on the next blog post. We can make this simple by using @staticmethod decorator

1
2
3
4
5
6
7
class Hello:
    @staticmethod
    def result(self, name):
        print("Hello " + name)

if __name__ == "__main__":
    Hello.result("", "Yodi")

Will give same results with previous example. Using @staticmethod on the function, that means we make the method callable without instantiating the class. Fyi, @staticmethod will executed the method in parent class if we calling the static method from subclass (child).

Like:

1
2
3
4
5
6
7
8
9
10
class Hello:
    @staticmethod
    def result(self, name):
        print("Hello " + name)

class World(Hello):
    pass

if __name__ == "__main__":
    World.result("", "Yodi")

Which this will gave same results as previous example. It’s fun to play with static method in Python


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.