[Tutor] what is @classmethod and @staticmethod ??

Tony Cappellini cappy2112 at gmail.com
Mon Mar 24 00:11:33 CET 2008


Kent

Would you show the examples which show where staticmethod &
classmethod are used?

I've often wondered about the usefulness of these myself. Having read
many of the popular books on python, none provide a good clear
explanation
of why or where these should be used, and what the alternatives are
(if any). They typically show an extremely terse example of the syntax
with little explanation.


Message: 7
Date: Sun, 23 Mar 2008 18:26:26 -0400
From: Kent Johnson <kent37 at tds.net>
Subject: Re: [Tutor] what is @classmethod and @staticmethod ??
To: maser <maseriyer at yahoo.com>
Cc: tutor at python.org
Message-ID: <47E6D912.1050801 at tds.net>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

maser wrote:
> Thanks, Andreas. Why do we need to use classmethod/
> staticmethod and where do we need to use them ?

I use staticmethods as a convenience to put related functions in the
namespace of a class. Perhaps foo.py contains class Foo with
staticmethod bar(). In client code I can say

from foo import Foo
Foo.bar()

If bar was a module method it would be

from foo import Foo, bar
bar()


I prefer the former in cases where bar is related to Foo.

Kent


More information about the Tutor mailing list