instance + classmethod question

Steven Bethard steven.bethard at gmail.com
Sun Dec 11 22:23:35 CET 2005


Laszlo Zsolt Nagy wrote:
> In my methods, most code is about string manipulation and calling other 
> classmethods.
> There are only a few places where I can use an instance, but it is not 
> required.
> I would like to reuse as most code as possible, so I do not want to 
> create two different
> methods. That would result in duplicating code.

I would tend to do this by creating a wrapper method for the instance 
that did the appropriate stuff for the instance, and then called the 
classmethod, e.g.:

class C(object):
    ...
    @classmethod
    def do_stuff(cls, *args):
        ...
    def do_instance_stuff(self, *args):
        # instance stuff
        ...
        self.do_stuff(*args)
        # more instance stuff
        ...

But it does require some factoring of the classmethod so that it makes 
sense to call it in this manner.

STeVe



More information about the Python-list mailing list