[Tutor] Class vs. Static Methods

Kent Johnson kent37 at tds.net
Wed Jun 22 12:39:38 CEST 2005


Alan G wrote:
> So If I have a heirarchy of shapes and want a class method that
> only operates on the shape class itself, not on all the
> subclasses then I have to use staticmethod whereas if I want
> the class method to act on shape and each of its sub classes
> I must use a classmethod. The canonical example being counting
> instances. staticmethod would only allow me to count shapes
> but class method would allow me to count all the sub classes
> separately. 

Sounds good so far.

Mind you this would require reprogramming the
> class method for each new shape which is probably a bad
> idea - overriding would be a better approach IMHO...

Not sure why you think you have to write a new classmethod for each shape. Suppose you want to maintain creation counts for each class. Here is one way to do it using classmethods:

class Shape(object):
  _count = 0    # Default for classes with no instances (cls.count() never called)
  
  @classmethod
  def count(cls):
    try:
      cls._count += 1
    except AttributeError:
      cls._count = 1
      
  @classmethod
  def showCount(cls):
    print 'Class %s has count = %s' % (cls.__name__, cls._count)
    
  def __init__(self):
    self.count()

class Point(Shape): pass

class Line(Shape): pass

p, p2, p = Point(), Point(), Point()
Point.showCount()

Line.showCount()
l = Line()
Line.showCount()


### prints
Class Point has count = 3
Class Line has count = 0
Class Line has count = 1


Kent



More information about the Tutor mailing list