Inheriting and modifying lots of methods

Diez B. Roggisch deets at nospam.web.de
Tue Oct 27 13:51:02 EDT 2009


Felipe Ochoa wrote:

> I need to create a subclass from a parent class that has lots of
> methods, and need to decorate all of these. Is there pythonic way of
> doing this other than:
> 
> def myDecorator (meth):
>     @wraps(meth)
>     def newMeth (*args, **kw):
>         print("Changing some arguments here.")
>         return meth(newargs, **kw)
>     return newMeth
> 
> class Parent:
>     def method1(self,args):
>         pass
>     def method2(self,args):
>     # and so on...
>     def methodn(self,args):
>         pass
> 
> class Mine(Parent):
>     for thing in dir(Parent):
>         if type(eval("Parent."+thing)) == type(Parent.method1):
>             eval(thing) = myDecorator(eval("Parent." + thing))
> 
> I'm not even sure that this works! Thanks a lot!

It's not working, you can't assign to something eval'ed.

There are various options here, including metaclasses, but I think the
simplest is to write a simple function:

def decorate_methods(subclass):
    for name in dir(subclass):
        thing = getattr(subclass, name)
        if isinstance(thing, types.MethodType):
           setattr(subclass, name, myDecorator(thing)) # maybe
myDecorator(thing.im_func) is better here


Simply invoke that function with "Mine" - or use a metaclass to do that
implicitly.

Diez



More information about the Python-list mailing list