Class Methods Vs Any Other Callable

George Sakkis george.sakkis at gmail.com
Thu May 15 02:56:48 EDT 2008


On May 14, 4:38 pm, "bruno.desthuilli... at gmail.com"
<bruno.desthuilli... at gmail.com> wrote:
> On 14 mai, 16:30, George Sakkis <george.sak... at gmail.com> wrote:
>
> > On May 14, 10:19 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>
> > > > An instance method works on the instance
> > > > A Static method is basically a function nested within a class object
> > > > A class method is overkill?
>
> > > If anything, a static method is overkill. See it this way: *if* you for some
> > > reason put a method into an enclosing context - isn't it worth having a
> > > reference to that?
>
> > My feeling exactly; these days I almost always use class methods
> > instead of static. I vaguely remember seeing somewhere an example
> > where a static method was the only (elegant) solution; neither a class
> > method nor a plain function would do. I'll post it if I find it unless
> > someone beats me to it.
>
> No concrete example here but I surely remember having used
> staticmethods in one case where I needed class-based polymorphic
> dispatch and eventually implementation inheritance (to get a default
> implementation)  for something that didn't required access to the
> class object.

Yes, that's common, but a class method could be used just as well
here. I couldn't find the original example but IIRC it was related to
monkeypatching. Say that you have a package P1 that has some useful
classes:

    class A(object): pass
    class B(A): pass
    class C(A): pass

You also have an unrelated package P2 with some useful functions:

    def f1(): return 0
    def f2(): return 1

Naturally you want to combine these two. One common pattern when doing
so turns out to be like:

    # e.g. x = random.choice([A(), B(), C()])
    ...
    assert isinstance(x, A)
    if type(x) in (A,B):
        print f1()
    elif type(x) is C:
        print f2()

With a less trivial hierarchy and number of functions, it becomes
clear that it would help a lot if you could refactor it somehow so you
can just say "print x.f()" and it would do the right thing.
Monkeypatching it as a normal method ("A.f = f1; C.f = f2") doesn't
work because it expects self as the first argument, and similarly for
class methods and the cls argument. OTOH static methods do the trick:

    A.f = staticmethod(f1)
    C.f = staticmethod(f2)
    print x.f()

Admittedly it's not a common scenario but it's good to know it's there
if you need it.

George



More information about the Python-list mailing list