开发者

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

开发者 https://www.devze.com 2022-12-27 19:51 出处:网络
How do I add a method with a decorator to a class?I tried def add_decorator( cls ): @dec def update(self):

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 doe开发者_StackOverflows not have the decorator

@dec did not apply to update

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


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


In the class that represents your SQL record,

from sqlalchemy.orm import reconstructor

class Thing(object):
    @reconstructor
    def reconstruct(self):
        pass
0

精彩评论

暂无评论...
验证码 换一张
取 消