Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a class of a method?

I created a decorator for a method in my class, but inside the decorator, I need to get the class of the method. How can I do that?

Here is the code of what I am trying to do:


def my_decorator(method):
    a = # The class of "method"
    print(a)  # <class '__main__.MyClass'>

class MyClass:
    @my_decorator
    def my_method(self, *args, **kwargs):
        ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First you need to fix the decorator… you get the reference of the class as the first argument passed to the __wrapper. To get the parameter identifier you can use a code object and then use it as the key of locals.

Notice that this method is sensible on the signature of the decorator. In this case the last [0] is needed only because the first argument is *args,a tuple, and the first entry is needed.

def my_decorator(method):
    def __wrapper(*args, **kwargs):
        cls = locals()[__wrapper.__code__.co_varnames[0]][0]

        print(type(cls))
        print(hasattr(cls, method.__name__))
        return method(*args, **kwargs)
    return __wrapper


class MyClass:
    @my_decorator
    def my_method(self, *args, **kwargs):
        pass


MyClass().my_method()

Output

<class '__main__.MyClass'>
True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading