Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a method with a decorator to a class in python?

How do I add a method with a decorator to a class? I tried

def add_decorator( cls ):
    @dec
    def update(self):
        pass

    cls.update = update

usage

 add_decorator( MyClass )

 MyClass.update()

but MyClass.update does not have the decorator

@dec did not apply to update

I'm trying to use this with orm.reconstructor in sqlalchemy.

like image 280
Timmy Avatar asked Apr 24 '10 04:04

Timmy


1 Answers

If you want class decorator in python >= 2.6 you can do this

def funkyDecorator(cls):
    cls.funky = 1

@funkyDecorator
class MyClass(object):
    pass

or in python 2.5

MyClass = funkyDecorator(MyClass)

But looks like you are interested in method decorator, for which you can do this

def logDecorator(func):

    def wrapper(*args, **kwargs):
        print "Before", func.__name__
        ret = func(*args, **kwargs)
        print "After", func.__name__
        return ret

    return wrapper

class MyClass(object):

    @logDecorator
    def mymethod(self):
        print "xxx"


MyClass().mymethod()

Output:

Before mymethod
xxx
After mymethod

So in short you have to just put @orm.reconstructor before method definition

like image 54
Anurag Uniyal Avatar answered Oct 06 '22 20:10

Anurag Uniyal