[Tutor] Class vs. Static Methods
Chuck Allison
chuck at freshsources.com
Thu Jun 23 02:18:10 CEST 2005
Hello Kent,
This is the killer example I've been looking for. Now I understand.
Sorry I've been so dense. This is way cool. Thanks.
Wednesday, June 22, 2005, 4:39:38 AM, you wrote:
KJ> Not sure why you think you have to write a new classmethod for
KJ> each shape. Suppose you want to maintain creation counts for each
KJ> class. Here is one way to do it using classmethods:
KJ> class Shape(object):
KJ> _count = 0 # Default for classes with no instances (cls.count() never called)
KJ> @classmethod
KJ> def count(cls):
KJ> try:
KJ> cls._count += 1
KJ> except AttributeError:
KJ> cls._count = 1
KJ> @classmethod
KJ> def showCount(cls):
KJ> print 'Class %s has count = %s' % (cls.__name__, cls._count)
KJ> def __init__(self):
KJ> self.count()
KJ> class Point(Shape): pass
KJ> class Line(Shape): pass
KJ> p, p2, p = Point(), Point(), Point()
KJ> Point.showCount()
KJ> Line.showCount()
KJ> l = Line()
KJ> Line.showCount()
KJ> ### prints
KJ> Class Point has count = 3
KJ> Class Line has count = 0
KJ> Class Line has count = 1
KJ> Kent
--
Best regards,
Chuck
More information about the Tutor
mailing list