What is class method?

Raymond Hettinger python at rcn.com
Tue Aug 26 17:52:24 EDT 2008


On Aug 24, 5:32 am, Hussein B <hubaghd... at gmail.com> wrote:
> Hi,
> I'm familiar with static method concept, but what is the class method?
> how it does differ from static method? when to use it?

I use them when I need alternative constructors for a class.

class Angle(object):

   def __init__(self, degrees):
      self.degrees = degrees

   @classmethod
   def from_radians(cls, radians):
      return cls(radians / pi * 180.0)

This lets me construct a new angle with either Angle(45) or
Angle.from_radians(pi/4).

The example shows what is special about classmethods.  The first
argument is a class, not an instance.


Raymond



More information about the Python-list mailing list