[Edu-sig] More on decorators
kirby urner
kirby.urner at gmail.com
Tue Apr 1 15:42:11 CEST 2008
> I do use staticmethod, and I've got some good examples at http://ece.arizona.edu/~edatools/Python/Animals.py, but never saw a real need for classmethod. Your example at least makes the utility plausible, although I could easily do the same without a classmethod. But I think I see what you are trying to do. Maybe you could expand the example a bit to make it more compelling. In the current example, the variable klass has only one value, Register. You could have multiple classes (Retail, Wholesale, etc.) to drive home that klass really is an important variable, and can't just be hard-coded as Register.
>
Hi Dave --
Good questions!
I think the staticmethod vs. classmethod topic, decorators aside,
is a good one, I hope we do more on it.
Here's your Animals.py with classmethod in place of staticmethod.
Works about the same. But I won't say "this answers your question"
-- just adds more grist to the mill at this point.
class Animal(object):
"Ancestor of the Animal hierarchy"
_numAnimals = 0
home = "Earth"
def __init__(self):
Animal._numAnimals += 1
@classmethod
def show(klass):
print "Inventory:"
print " Animals:", klass._numAnimals
class Reptile(Animal): pass
class Mammal(Animal):
_numMammals = 0
basal_metabolic_rate = 7.2
def __init__( self, s = "Maa... Maa..."):
Animal.__init__(self)
Mammal._numMammals += 1
self.sound = s
@classmethod
def show(klass):
Animal.show()
print " Mammals:", klass._numMammals,
print " BMR =", klass.basal_metabolic_rate
def talk(self):
print "Mammal sound: ", self.sound
class Bovine(Mammal): pass
class Canine(Mammal): pass
class Feline(Mammal):
_numFelines = 0
genus = "feline"
def __init__( self):
Mammal.__init__(self)
Feline._numFelines += 1
@classmethod
def show(klass):
Mammal.show()
print " Felines:", klass._numFelines
class Cat(Feline):
_numCats = 0
def __init__( self, n = "unknown", s = "Meow" ):
Feline.__init__(self)
Cat._numCats += 1
self.name = n
self.sound = s
@ classmethod
def show(klass):
Feline.show()
print " Cats:", klass._numCats
def talk(self):
print "My name is ...", self.name
print "I am a %s from %s" % (self.genus, self.home)
Mammal.talk(self)
def test():
a = Animal()
m = Mammal(); print "m:",; m.talk()
f = Feline(); print "f:",; f.talk()
c = Cat(); print "c:",; c.talk()
print "--- Cat.show() ---"
Cat.show()
print "--- cat1.talk() ---"
cat1 = Cat("Garfield", "Purr")
cat1.talk()
if __name__ == '__main__':
test()
Kirby
More information about the Edu-sig
mailing list