Trying to come to grips with static methods
cyril.bazin at gmail.com
Tue Jul 12 11:33:57 CEST 2005
Ok, sorry, you are right Robert.
What about this one:
if type(p) == str:
if len(p) == 1:
toParser = staticmethod(toParser)
This is meant to translate p to a parser if it's not one.
'lit' is a function that take a string of length 1 and return a parser of
'txt' is a function that take a string of any length and return a parser.
I hope it is a better example!
That one of the rare case I used static method in Python...
On 7/12/05, Robert Kern <rkern at ucsd.edu> wrote:
> Cyril Bazin wrote:
> > (sorry, my fingers send the mail by there own ;-)
> > Im my opinion, class method are used to store some functionalities
> > (function) related to a class in the scope of the class.
> > For example, I often use static methods like that:
> > class Point:
> > def __init__(self, x, y):
> > self.x, self.y = x, y
> > def fromXML(xmlText):
> > x, y = functionToParseXMLUsingMinidomForExample(xmlText)
> > return Point(x, y)
> > fromXML = staticmethod(fromXML)
> > Here, it is used to define some kind of second constructor...
> > Note that class decorator can simplify the notation, but break the
> > compatility with older Python...
> Huh? classmethod was introduced with staticmethod, and in fact, this use
> case is exactly what classmethods are for, not staticmethods.
> In : class Point(object): # <-- note inheritance from object
> ...: def __init__(self, x, y):
> ...: self.x, self.y = x, y
> ...: def fromXML(cls, xmlText):
> ...: x, y = parseXML(xmlText)
> ...: return cls(x, y)
> ...: fromXML = classmethod(fromXML)
> In : class NewPoint(Point):
> ...: pass
> In : def parseXML(xmlText):
> ...: return 1, 4
> In : p = NewPoint.fromXML('<point x="1" y="4"></point>')
> In : isinstance(p, NewPoint)
> Out: True
> Robert Kern
> rkern at ucsd.edu
> "In the fields of hell where the grass grows high
> Are the graves of dreams allowed to die."
> -- Richard Harter
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list