As I've shown you in previous episode about parameterizing decorators you can create a class-based decorator.

This time let's create a derivation class-based decorator that is intended for classes.

To The Point

First, we create our class that will use decorator.

class MyFancyClassTest():

    def fancy_method(self):
        print("fancy print from fancy method")

The decorator itself with class:

class DecoratorForClasses(object):
    def __init__(self, klas):
        self.klas = klas
        self.org_fancy_method = self.klas.fancy_method
        self.klas.fancy_method = self.fancy_method
        print("init")

    def __call__(self, arg=None):
        print("call")
        return self.klas.__call__()

    def fancy_method(self):
        print("before pancy method (at decorator)")
        self.org_fancy_method(self.klas)
        print("after pancy method (at decorator)")


@DecoratorForClasses
class MyFancyClassTest():

    def fancy_method(self):
        print("fancy print from fancy method")

fancy_object = MyFancyClassTest()
fancy_object.fancy_method()

After analizing this, I see a lot of similarities with python-inherintance in it.

Yet since decorator does not have any other inheritance, but instead can "extend" capabilities of classes, it is still useful.

Snippets

class DecoratorForClasses(object):
    def __init__(self, klas):
        self.klas = klas
        self.org_method1 = self.klas.method1
        self.klas.method1 = self.method1

    def __call__(self, *args, **kwargs):
        return self.klas.__call__(*args, **kwargs)

    def method1(self, *args, **kwargs):
        print("method1_decorator")
        output = self.org_method1(self.klas, *args, **kwargs)
        return output


@DecoratorForClasses
class MyFancyClassTest():

    def method1(self):
        print("fancy print from fancy method")

fancy_object = MyFancyClassTest()
fancy_object.method1()

Acknowledgements

Auto-Promotion

Related links

Thanks!

That's it :) Comment, share or don't :)

If you have any suggestions what I should blog about in the next articles - please give me a hint :)

See you in the next episode! Cheers!



Comments

comments powered by Disqus