开发者

Redefine or add Methods to class through decorator. Possible?

开发者 https://www.devze.com 2023-03-20 05:00 出处:网络
I have class: @custom_decorator class Creature(objects): def __init__(self): pass def rise_hands(self, *args, **kwargs):

I have class:

@custom_decorator
class Creature(objects):

    def __init__(self):
        pass

    def rise_hands(self, *args, **kwargs):
        print 'hands rised'

I want to define the custom decorator on the top of this class Creature, so that it will redefine the method rise_hands or adds new methods.

By the way: how can I redefine the values of args or kwargs?

UPDATE:

The gola is as follow: I wanna implement an app with decorator for django models开发者_Python百科. Whatever i define it on the model it will log changes by saving old values and new values of curten fields...


Don't. Do. This.

You have inheritance to do exactly what you're talking about.

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"

This is the way you "redefine the method rise_hands or adds new methods"


Here's how you can modify arguments in kwargs and args. I don't see anything wrong with doing this in principle

>>> 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), {})
0

精彩评论

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

关注公众号