decorating a method in multiple child classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • 1x7y2z9@gmail.com

    decorating a method in multiple child classes


    Say, we have a (parent) class P.
    It has N child classes C1(P), C2(P) ... CN(P)

    Each of the child classes defines (differently) a method func().

    I wish to decorate all of the CX.func() in the same way. One way to
    do this is to add a decorator to each of the derived classes. But
    this is tedious and involves modifying multiple files.

    Is there a way to modify the parent class and have the same effect?
    Or some other way neater than the above?

    Thanks.



    visual:
    class P(object):
    ...

    class C1(P):
    def func(self, ...):
    ...

    class C2(P):
    def func(self, ...):
    ...
  • Duncan Booth

    #2
    Re: decorating a method in multiple child classes

    1x7y2z9@gmail.c om wrote:
    I wish to decorate all of the CX.func() in the same way. One way to
    do this is to add a decorator to each of the derived classes. But
    this is tedious and involves modifying multiple files.
    >
    Is there a way to modify the parent class and have the same effect?
    Or some other way neater than the above?
    >
    Use a metaclass.
    >>def decorate(f):
    print "decorating ", f
    return f
    >>class meta(type):
    def __init__(self, name, bases, dictionary):
    if 'func' in dictionary:
    dictionary['func'] = decorate(dictio nary['func'])
    type.__init__(s elf, name, bases, dictionary)

    >>class P(object):
    __metaclass__ = meta

    >>class C1(P):
    def func(self): pass


    decorating <function func at 0x0119B370>
    >>>

    Comment

    Working...