[Tutor] what is @classmethod and @staticmethod ??
Kent Johnson
kent37 at tds.net
Mon Mar 24 00:34:34 CET 2008
Tony Cappellini wrote:
> Kent
>
> Would you show the examples which show where staticmethod &
> classmethod are used?
Some good discussion here:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/56ee49c203fd72e2/922f84d9d26662fc?hl=en&lnk=gst&
I don't use classmethods so I can't discuss that. For staticmethods,
suppose I have in foo.py
class Foo(object):
# Lots of useful stuff
In client.py I have
from foo import Foo
# Do interesting things with Foo
Now perhaps I need a function
doSomethingRelatedToFoo()
that belongs in foo.py but doesn't have to be an instance method - it is
just a related function. I could make this a module function and change
client.py to read
from foo import Foo, doSomethingRelatedToFoo
doSomethingRelatedToFoo()
or I could make doSomethingRelatedToFoo a staticmethod, then I don't
have to change the import statement, I can access
doSomethingRelatedToFoo() through the already-imported Foo class:
Foo.doSomethingRelatedToFoo()
It's a pretty small difference but I like keeping the import simple and
not having to change it when I add doSomethingRelatedToFoo() to foo.py.
Kent
More information about the Tutor
mailing list