[Tutor] how do you use __dict__ ? (Was: code dangerous?)

Alfred Milgrom fredm@smartypantsco.com
Thu Jan 9 20:07:01 2003


At 04:03 PM 8/01/03 +0000, you wrote:
>This should read:
>
>__speak = self.__dict__.get('my_speak')
>
>[rest snipped]

Thanks for the update - looks interesting, but I don't know anything 
about  using __dict__, or understand what __speak means.
I couldn't find any good references, so I just tried something anyway :(

My attempt at implementing this code works, but seems like a heavy-handed 
way to use 'magic' attributes:

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

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

     def speak(self):
         __speak = self.__dict__.get('my_speak')
         if __speak:
             eval(__speak)
         else:
             print "%s says: my name is %s" % (self.name, self.name)

     def crankyspeak(self):
         print "%s says: I don't tell anyone my name" % (self.name)

hobbit = Person('Bilbo Baggins')

cranky = Person('someone else')
cranky.__dict__['my_speak'] = 'self.crankyspeak()'

hobbit.speak()
cranky.speak()

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

Can you suggest any good links or explain how I am supposed to use __dict__ 
and __speak ?

Thanks,
Fred