[Tutor] is this code dangerous?

Alfred Milgrom fredm@smartypantsco.com
Wed Jan 8 08:17:02 2003


Hi:

Can someone please tell me the best way to override class methods for 
specific instances?

I want to have a general class, such as Person, with general methods. Some 
of the instances of the Person class may have different methods, and I want 
to be able to override the base method (such as the speak method for the 
cranky person in the example below).

Do I need to define a new class for each instance where there is a 
different method? Is there overhead associated with having a large number 
of classes?

Is the following code dangerous? (Obviously I could change the name of the 
cranky class to crankyperson, or something like that, and have a different 
class for each instance). What is the best way to handle this?

************************

class Person:
     def __init__(self, name):
         self.name = name

     def speak(self):
         print "%s says: my name is %s" % (self.name, self.name)

hobbit = Person('Bilbo Baggins')

class cranky(Person):
     def speak(self):
         print "%s says: I don't tell anyone my name" % (self.name)

cranky = cranky('someone else')

hobbit.speak()
cranky.speak()

************************

Thanks in advance,
Fred Milgrom