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

Andreas Kostyrka andreas at kostyrka.org
Mon Mar 24 23:51:12 CET 2008

A classical example is a class that can be constructed from different

Ok, let's implement a special integer class:

class MyOwnInteger(object):
    def __init__(self, value):
        self.value = value

Now, let's say we want to add the possibility to create MyOwnInteger
instances from strings. We can accomplish this by checking the type of
value inside of __init__, but this does not scale if there might be
different interpretations for a string:

class MyOwnInteger(object):
    def __init__(self, value):
        self.value = value
    def fromString(cls, value):
        return cls(int(value))
    def fromFiledata(cls, filename):
        fp = file(filename)
        data = fp.read()
        return cls(int(data.strip()))


Am Sonntag, den 23.03.2008, 16:11 -0700 schrieb Tony Cappellini:
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20080324/f7583512/attachment.pgp 

More information about the Tutor mailing list