why static methods?
vze4rx4y at verizon.net
Fri Feb 21 07:23:42 CET 2003
"Greg Ewing (using news.cis.dfn.de)" <me at privacy.net> wrote in message
news:b347v6$1g1c2c$1 at ID-169208.news.dfncis.de...
> Uwe Schmitt wrote:
> > Can you explain the differences
> > between static- and class-functions, too ?
> A class method is like a static method except that it
> is passed the class as its first parameter when called,
> much like an ordinary method is passed the instance
> when called.
Class methods are particularly useful for creating
an alternative constructors. Here is an example
with a Triangle object that can be constructed
from three sides or from two sides and an
>>> class Triangle:
def __init__(self, s1, s2, s3):
self.s1 = s1
self.s2 = s2
self.s3 = s3
return self.s1 + self.s2 + self.s3
def SAS(cls, s1, angle, s2):
s3 = (s1**2 + s2**2 - 2 * s1 * s2 * math.cos(angle)) ** 0.5
return cls(s1, s2, s3)
SAS = classmethod(SAS)
>>> t = Triangle.SAS(3, 3.14159 / 2, 4)
More information about the Python-list