Class Methods Vs Any Other Callable
Diez B. Roggisch
deets at nospam.web.de
Wed May 14 10:19:45 EDT 2008
> 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?
> I can call a static or class method through either the class OR any
> instance of it. I've never designed a method that took advantage of
> the class name except in cases where I needed to extend a super class
> *but* even in this case, I didn't use the enclosing class name...
>
> Whats the deal with class methods, why use them over anything else?
> What does a class method accomplish in at least one line shorter than
> anything else? Does it help reduce duplication or typing? I am at a
> lost for words that can shed at least *one* good reason to use them.
>
> What is the one greatest reason to use them? A little syntax and
> explanation can go a long long way. I am failing to understand them so
> any help is really appreciated here!
There is not one greatest reason. They have their uses as e.g.
factory-methods for instances of the class. Or as e.g. registering
functions for notifications amongst instances of the class. In which case
writing
class Foo:
@classmethod
def register(cls, listener):
cls.LISTENERS.append(listener)
is much more robust because you could rename Foo the way you like - register
won't be affected.
Diez
More information about the Python-list
mailing list