Python 通过decorator重新定义或向类添加方法。可能的
我有课:Python 通过decorator重新定义或向类添加方法。可能的,python,decorator,Python,Decorator,我有课: @custom_decorator class Creature(objects): def __init__(self): pass def rise_hands(self, *args, **kwargs): print 'hands rised' 我想在这个类的顶部定义自定义装饰器,这样它就可以重新定义方法rise\u hands,或者添加新的方法 顺便问一下:我如何重新定义args或kwargs的值 更新: gola如下所示
@custom_decorator
class Creature(objects):
def __init__(self):
pass
def rise_hands(self, *args, **kwargs):
print 'hands rised'
我想在这个类的顶部定义自定义装饰器,这样它就可以重新定义方法rise\u hands
,或者添加新的方法
顺便问一下:我如何重新定义args
或kwargs
的值
更新:
gola如下所示:
我想为django模型实现一个带有decorator的应用程序。无论我在模型上定义了什么,它都会通过保存curten字段的旧值和新值来记录更改 不要。做这个 你必须完全按照你所说的去做
class FancyCreature( Creature ):
def __init__(self):
super( FancyCreature, self ).__init___()
def rise_hands(self, *args, **kwargs):
print 'hands rised'
super( FancyCreature, self ).rise_hands( *args, **kwargs )
def new_method( self ):
print "new method"
这是您“重新定义方法
举手
或添加新方法”的方式。以下是如何修改kwargs和args中的参数。原则上我不认为这样做有什么错
>>> def go(func,*args,**kwargs):
... def g(*args,**kwargs):
... func(args+(1,),kwargs)
... return g
...
>>> @go
... def rise_hands(*args, **kwargs):
... print args
...
>>> rise_hands(1)
((1, 1), {})
在Python 3中,您只需在类中使用
super().[method]
,而无需传递类名和self
。我知道,但在我的例子中,我想重新定义django模型保存方法的行为,或者重新定义字段的getter,以便在每次更改时记录新旧值。。。或者类似这样:)…为什么要像这样混淆代码?“通过保存某些字段的旧值和新值来记录更改”。这就是Djangopre_save
signal的作用。