Decorating a parent class method

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)


Asked by: Daryl809 | Posted: 28-01-2022






Answer 1

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.

Answered by: Kellan666 | Posted: 01-03-2022



Answer 2

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

Answered by: Vivian456 | Posted: 01-03-2022



Answer 3

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)?

Answered by: Lucas520 | Posted: 01-03-2022



Similar questions

python - Decorating a method

In my Python app, I'm using events to communicate between different plugins. Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me. I would like to have it look like this: @events.listento('event.name') def myClassMethod(self, event): ... I have first tried to do it like this: def listento(to): def...


python - Decorating a DBUS method

I'm trying to combine DBUS' asynchronous method calls with Twisted's Deferreds, but I'm encountering trouble in tweaking the usual DBUS service method decorator to do this. To use the DBUS async callbacks approach, you'd do: class Service(dbus.service.Object): @dbus.service.method(INTERFACE, async_callbacks=('callback', 'errback')) def Resources(self, callback, errback): callback({'...


python - how to know if I'm decorating a method

It seems that mymethod is not yet a method when the decorator is called. import inspect class decorator(object): def __call__(self, call): if inspect.ismethod(call): #Not working yet obj = "method" args = inspect.getargspec(call)[0][1:] elif inspect.isfunction(call): obj = "function" args = inspect.getargspec(call)[0] elif inspect....


python - Decorating a class method with a class method

I was decorating a class method with another class method. The class looks like this from functools import wraps class MyClass(object): def __init__(self): print('Within my class object') def my_decorator(func_to_decorate): @wraps(func_to_decorate) def wrapper(self): print('Before the call') func_to_decorate(self) print('After the funct...


Python decorating class

I'm trying to decorate a class with arguments but cannot get it to work: This is the decorator: def message(param1, param2): def get_message(func): func.__init__(param1,param2) return get_message class where I want to put the decorator @message(param1="testing1", param2="testing2") class SampleClass(object): def __init__(self): p...


decorator - Python decorating functions before call

I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?


django - Decorating Instance Methods in Python

Here's the gist of what I'm trying to do. I have a list of objects, and I know they have an instance method that looks like: def render(self, name, value, attrs) # Renders a widget... I want to (essentialy) decorate these functions at runtime, as I'm iterating over the list of objects. So that their render functions become this: def render(self, name, value, attrs) se...


python - Decorating a method

In my Python app, I'm using events to communicate between different plugins. Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me. I would like to have it look like this: @events.listento('event.name') def myClassMethod(self, event): ... I have first tried to do it like this: def listento(to): def...


python - Decorating a class method after @property

I want to wrap every method of various objects except __init__ using a decorator. class MyObject(object): def method(self): print "method called on %s" % str(self) @property def result(self): return "Some derived property" def my_decorator(func): def _wrapped(*args, **kwargs): print "Calling decorated function %s" % func return func(*args, **kw...


python - Decorating a DBUS method

I'm trying to combine DBUS' asynchronous method calls with Twisted's Deferreds, but I'm encountering trouble in tweaking the usual DBUS service method decorator to do this. To use the DBUS async callbacks approach, you'd do: class Service(dbus.service.Object): @dbus.service.method(INTERFACE, async_callbacks=('callback', 'errback')) def Resources(self, callback, errback): callback({'...


python - decorating recursive functions

I have a decorator that I wrote that will time a given function. It seems to work well with any function, except for recursive functions. Decorator: def tictoc(repeats=3, loops=1): def t(func): from functools import partial, wraps import timeit @wraps(func) def timer(*args, **kargs): elapsed = timeit.repeat(partial(func, *args, **kargs), repeat = repe...


Class Decorator decorating method in python

This question already has answers here:


python - Decorating a method - how to call the method in oo fashion instead of procedural fashion

Following up on an earlier thread my question is how can I take this expression: fn(self,*args, **kwargs and call it in oo fashion like this self.fn(...) here is my total program with the failing line commented out: def formatHeader(fn): def wrapped(*args, **kwargs): print ...


python - How create decorator in Django for decorating view

I have view: @decorator def func(request): hello = "hello" return render_to_responce("test.html", locals() ) and template test.html: {{ hello }} {{ username }} I want to write decorator for func(request), which adds a variable, USERNAME, to the function and returns two parameters in the template. I tried to make it as follows:


python - preserve argspec when decorating?

This question already has answers here:






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top