How to add method to a class using decorator in Python


Python - Add method to a class using decorator

To add method to a class in Python, you can use class decorator.

Here is an example of a class decorator.

Python Program

def add_method(cls):
    def square(self, x):
        return x**2
    cls.square = square
    return cls

@add_method
class Calculator:
    pass

calc = Calculator()
print(calc.square(5))

Output

25

In the code

We defined a class decorator add_method that adds a new method square to the class it is applied to. The square method takes a single argument x and returns its square.

The add_method decorator takes a class as its argument, defines the square method, adds it to the class using the cls.square = square syntax, and returns the modified class.

We apply the decorator to the Calculator class using the @add_method syntax. When we create an instance of Calculator and call the square method on it, we get the expected output of 25, which is the square of 5.

References

Summary

In this tutorial, we learned how to define a decorator that adds a method to a class, with examples.