[Tutor] is this code dangerous?
Alfred Milgrom
fredm@smartypantsco.com
Wed Jan 8 23:02:01 2003
Thanks to everyone who helped me out with this question.
>What do you mean by dangerous?
What I meant by 'dangerous' was that I had named the class 'cranky', and
then threw away the reference by naming the instance 'cranky' as well.
Anyway, I just wanted to share the solution that I think I will adopt:
**************************************************
class Person:
def __init__(self, name):
self.name = name
def speak(self, dummy):
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.speak=Person.crankyspeak
hobbit.speak(hobbit)
cranky.speak(cranky)
**************************************************
The benefits from my point of view are:
* I don't have to create a large number of classes
* all the code for the methods are in the one place (Person class)
* I can easily mix and match the methods for any instance without the
difficulties that Alan mentioned
* the same code structure (albeit more unwieldy than usual) can be used for
every instance/method combination (ie no problems with unbound methods or
not passing self parameter)
Thanks again for your help,
Fred Milgrom