Python classes: Invoking different types of methods

Short read about invoking normal, class and static methods of a class using python

·

1 min read

Python classes: Invoking different types of methods

Here is a code snippet:

class TestClass:
    def normal_method(self):
        print("In normal method")

    @classmethod
    def class_method(cls):
        print("In class method")

    @staticmethod
    def static_method():
        print("In static method")

As you can see above, we have declared a class with 3 different types of methods. Now let's call them.

Method 1: Using the instance of the class

We call each of the methods in the usual way using the instance of the class.

t = TestClass()
t.normal_method()
t.class_method()
t.static_method()

# Output:
# In normal method
# In class method
# In static method

Method 2: Using the class

In the case of the class and static method, we can also call them using the class itself as shown below:

TestClass.class_method()
TestClass.static_method()

# Output:
# In class method
# In static method

We can also call the normal method using the class, but then we still need to pass the instance to the method

TestClass.normal_method(t)

# Output:
# In normal method

Conclusion

A normal method of a class has to be called using the instance of the class. On the other hand, static and class methods of a class can be called using both the instance of the class and the class itself.

Hope you found this article useful!