Python 2.2 class methods examples?

Martin v. Loewis martin at v.loewis.de
Tue Feb 12 05:09:27 EST 2002


kalath at lycos.com (Mark Brady) writes:

> Hi. I've just moved to 2.2 and I think I've got my head around most of
> the cool new features but I can't see what class methods would be used
> for. I understand the difference between them and static methods and I
> know where static methods are useful but it would be great if someone
> could post an example of class method usage or some links. Thanks.

One application is to use them as factory methods:

class Base:
  _allinstances = {}
  def byName(cls, name):
    try:
      return cls._allinstances[(cls,name)]
    except KeyError:
      return cls._allinstances.setdefault((cls,name), cls())
  byName = classmethod(byName)

class Derived(Base):
  pass

Then, Derived.byName("foo") will give you a Derived instance, namely
the same over and over again, but that will be different from
Base.byName("foo"), which is a Base instance.

Regards,
Martin




More information about the Python-list mailing list