Decorating a parent class method

Question!

I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but not in the parent class.

Essentially, I am trying to accomplish the following:

class foo(Object):
    def meth1(self, val):
        self.value = val

class bar(foo):
    meth1 = classmethod(foo.meth1)


Answers

What are you trying to accomplish? If I saw such a construct in live Python code, I would consider beating the original programmer.



I'm also not entirely sure what the exact behaviour you want is, but assuming its that you want bar.meth1(42) to be equivalent to foo.meth1 being a classmethod of bar (with "self" being the class), then you can acheive this with:

def convert_to_classmethod(method):
    return classmethod(method.im_func)

class bar(foo):
    meth1 = convert_to_classmethod(foo.meth1)

The problem with classmethod(foo.meth1) is that foo.meth1 has already been converted to a method, with a special meaning for the first parameter. You need to undo this and look at the underlying function object, reinterpreting what "self" means.

I'd also caution that this is a pretty odd thing to do, and thus liable to cause confusion to anyone reading your code. You are probably better off thinking through a different solution to your problem.

By : Brian


This video can help you solving your question :)
By: admin