Trying to come to grips with static methods

Cyril Bazin cyril.bazin at gmail.com
Tue Jul 12 11:33:57 CEST 2005


Ok, sorry, you are right Robert. 

What about this one: 

class Parser(object):
def toParser(p):
if type(p) == str:
if len(p) == 1:
return lit(p)
return txt(p)
return p
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 
char.
'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...

Cyril

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 [2]: 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 [3]: class NewPoint(Point):
> ...: pass
> ...:
> 
> In [4]: def parseXML(xmlText):
> ...: return 1, 4
> ...:
> 
> In [5]: p = NewPoint.fromXML('<point x="1" y="4"></point>')
> 
> In [6]: isinstance(p, NewPoint)
> Out[6]: 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
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050712/5ee01e6c/attachment.html>


More information about the Python-list mailing list