Trying to come to grips with static methods

Robert Kern rkern at ucsd.edu
Tue Jul 12 11:17:34 CEST 2005


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




More information about the Python-list mailing list