python 类方法装饰器_如何在python中向类中添加带装饰器的方法?

如何将类装饰器的方法添加到类中?我试过了

def add_decorator( cls ):

@dec

def update(self):

pass

cls.update = update

用法

add_decorator( MyClass )

MyClass.update()

但是MyClass.update没有装饰器

@dec不适用于更新

我正试图在sqlalchemy中使用orm.reconstructor.

解决方法:

如果你想在python> = 2.6中使用类装饰器,你可以这样做

def funkyDecorator(cls):

cls.funky = 1

@funkyDecorator

class MyClass(object):

pass

或者在python 2.5中

MyClass = funkyDecorator(MyClass)

但看起来你对方法装饰器感兴趣,你可以为此做到这一点

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()

输出:

Before mymethod

xxx

After mymethod

所以简而言之,你必须在方法定义之前放置@ orm.reconstructor

标签:python,decorator

来源: https://codeday.me/bug/20190518/1130291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值