[Tutor] is this code dangerous?

Gonçalo Rodrigues op73418@mail.telepac.pt
Thu Jan 9 12:45:55 2003


----- Original Message -----
From: "Gonçalo Rodrigues" <op73418@mail.telepac.pt>
To: <tutor@python.org>
Sent: Wednesday, January 08, 2003 4:02 PM
Subject: Re: [Tutor] is this code dangerous?


>
> ----- Original Message -----
> From: "Alfred Milgrom" <fredm@smartypantsco.com>
> To: <tutor@python.org>
> Sent: Wednesday, January 08, 2003 1:14 PM
> Subject: [Tutor] is this code dangerous?
>
>
> > 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?
> >
>
> Using the example you give below you can also do:
>
> >>> class Person:
> ...  def __init__(self, name):
> ...   self.name = name
> ...  def speak(self):
> ...   print "%s says: my name is %s" % (self.name, self.name)
> ...
> >>> Person
> <class __main__.Person at 0x0110A970>
> >>> cranky = Person('someone else')
> >>> def crankyspeak(self):
> ...  print "%s says: I don't tell anyone my name" % (self.name)
> ...
> >>> cranky.speak = crankyspeak
>
> But you have to notice though that speak is not a method but a plain
> function object: self is not automatically passed, e.g.
>
> >>> cranky.speak()
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: crankyspeak() takes exactly 1 argument (0 given)
> >>> cranky.speak(cranky)
> someone else says: I don't tell anyone my name
>
> There are ways of course to override this - e.g. using something like the
> template pattern. You could code something like
>
> class Person:
>     <whatever>
>
>     def speak(self):
>         __speak = self.et('my_speak')

This should read:

__speak = self.__dict__.get('my_speak')

[rest snipped]

With my best regards,
G. Rodrigues