[Tutor] is this code dangerous?

alan.gauld@bt.com alan.gauld@bt.com
Thu Jan 9 20:33:02 2003


> class Person:
>      def __init__(self, name):
>      def speak(self, dummy):
>      def crankyspeak(self):
> 
> hobbit = Person('Bilbo Baggins')
> cranky = Person('someone else')
> cranky.speak=Person.crankyspeak

The problem with this approach is twofold:
1) You just lost all the advantages of polymorphism 
because your code has to know when it has a cranky 
person and whne a normal person so that it knows which
version of speak() to call. This has bigger problems 
when you later want to add another type of speak method, 
you will wind up with lots of big if/elif/else chains 
potentially..

2) You may wind up writing code multiple times within 
each speak method rather than leveraging the existing 
code via inheritance or delegation.

> * I don't have to create a large number of classes

This really shouldn't be a big problem.

> * all the code for the methods are in the one place (Person class)

This is not necessarily a good thing. Especially as the 
behaviour of your person types grows increasingly diverse. 
You wind up with interleaved class definitions masquerading 
as a single class. Thios also leads to maintenance problems 
later since a bug fix to any method means retesting all of 
your person objects not just those of the changed class.


> * I can easily mix and match the methods for any instance without the 
> difficulties that Alan mentioned

Duid I mention many difficulties? There is a downside whichever 
way you go but the evils of supporting many classes are IMHO 
much less than in supporting a single multi behaved class

> * 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)

Within the class maybe but it adds more complexity in the 
client code. If your application using the person objects 
then you are likely to wind up writing more code in total 
rather than less.

Regards,

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/