Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-register class methods using decorator

Tags:

I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties).

Example code:

class my_class(object):      @register(prop1,prop2)     def my_method( arg1,arg2 ):        # method code here...      @register(prop3,prop4)     def my_other_method( arg1,arg2 ):        # method code here... 

I want that when loading is done, somewhere there will be a dict containing:

{ "my_class.my_method"       : ( prop1, prop2 )   "my_class.my_other_method" : ( prop3, prop4 ) } 

Is this possible?

like image 361
adamk Avatar asked Jun 16 '10 14:06

adamk


People also ask

How to define the decorator as a method class?

we have used the _call_ to define the decorator as a method class in the code. The _call_ method is used when a user creates an object to work as a function, and the decorator will return the object that works like a function.

What is @classmethod decorator in Python?

In Python, the @classmethod decorator is used to declare a method in the class as a class method that can be called using ClassName.MethodName () . The class method can also be called using an object of the class.

Is it possible to create decorators inside a class?

We can easily create decorators inside a class and it is easily accessible for its child classes.

How do you create a function in a decorator?

Create Decorators by passing functions as arguments to the class constructor To create a decorated function, We can pass the add() function as an input argument to the constructor of the decorator class. The add() function will be assigned to the funcvariable in the decorator_class.


1 Answers

Here's a little love for class decorators. I think the syntax is slightly simpler than that required for metaclasses.

def class_register(cls):     cls._propdict = {}     for methodname in dir(cls):         method = getattr(cls, methodname)         if hasattr(method, '_prop'):             cls._propdict.update(                 {cls.__name__ + '.' + methodname: method._prop})     return cls   def register(*args):     def wrapper(func):         func._prop = args         return func     return wrapper   @class_register class MyClass(object):      @register('prop1', 'prop2')     def my_method(self, arg1, arg2):         pass      @register('prop3', 'prop4')     def my_other_method(self, arg1, arg2):         pass  myclass = MyClass() print(myclass._propdict) # {'MyClass.my_other_method': ('prop3', 'prop4'), 'MyClass.my_method': ('prop1', 'prop2')} 
like image 70
unutbu Avatar answered Sep 17 '22 17:09

unutbu