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 <[EMAIL PROTECTED]> 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
[EMAIL PROTECTED]
"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
-- http://mail.python.org/mailman/listinfo/python-list