A classical example is a class that can be constructed from different values.
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 @classmethod def fromString(cls, value): return cls(int(value)) @classmethod def fromFiledata(cls, filename): fp = file(filename) data = fp.read() fp.close() return cls(int(data.strip())) Andreas 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 <[EMAIL PROTECTED]> > Subject: Re: [Tutor] what is @classmethod and @staticmethod ?? > To: maser <[EMAIL PROTECTED]> > Cc: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > 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@python.org > http://mail.python.org/mailman/listinfo/tutor
signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor