Pol
Pol

Reputation: 25585

Redefine or add Methods to class through decorator. Possible?

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. Whatever i define it on the model it will log changes by saving old values and new values of curten fields...

Upvotes: 0

Views: 671

Answers (2)

S.Lott
S.Lott

Reputation: 391962

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"

Upvotes: 1

dfb
dfb

Reputation: 13289

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

Upvotes: 0

Related Questions