tags:

views:

358

answers:

3

Not sure if what I want to accomplish is even possible, but I'd like to make a child class have a method of the parent class be a 'classmethod' even though the method in the parent class is not. Essentiall I'm trying to accomplish the following:

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

class bar(foo):
    meth1=classmethod(foo.meth1)
+3  A: 

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

John Millikin
+1  A: 

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.

Brian
A: 

The question, as posed, seems quite odd to me: I can't see why anyone would want to do that. It is possible that you are misunderstanding just what a "classmethod" is in Python (it's a bit different from, say, a static method in Java).

A normal method is more-or-less just a function which takes as its first argument (usually called "self"), an instance of the class, and which is invoked as ".".

A classmethod is more-or-less just a function which takes as its first argument (often called "cls"), a class, and which can be invoked as "." OR as ".".

With this in mind, and your code shown above, what would you expect to have happen if someone creates an instance of bar and calls meth1 on it?

bar1 = bar()
bar1.meth1("xyz")

When the code to meth1 is called, it is passed two arguments 'self' and 'val'. I guess that you expect "xyz" to be passed for 'val', but what are you thinking gets passed for 'self'? Should it be the bar1 instance (in this case, no override was needed)? Or should it be the class bar (what then would this code DO)?