Polymorphism the Python way

Alan Gauld alan.gauld at btinternet.com
Sun Aug 31 03:45:23 EDT 2003


On Sat, 30 Aug 2003 20:55:30 -0700, Daniel Klein
<danielk at aracnet.com> wrote:
> class Dead(object):
>     def getthing(self):
>         return self.deadthing
> 
> class Parrot(object):
>     def getthing(self):
>         return self.parrotthing
> 
> ...and then somewhere in some script I use...
> 
>     self.getthing()

I guess you mean 

object.getthing() since self would be inside a method...

> Isn't there a better way to do this in Python? I hate doing these
> 'get' type methods. The seem ugly to me.

This isn't really a Python issue but one of general OOD. Its bad
OOD practice to provide a getXXX method for every attribute just
because they exist. But if it is a genuine public feature of the
class - ie one of the objects responsibilities - to provide
'thing' information then 

object.getThing()

is a valid way to go.

Of course Python by default allows you to access the value
directly if you wish, and you can also use the new "property"
feature to hide the accessor method. And the name of the method
could be changed to use a naming convention:

class C:
   def __init__(s,t): s.myThing = t
   def thing(s): return s.myThing

My old OO mentor used to say:
"Methods support responsibilities, attributes support methods"
In other words only expose those attributes which are also
responsibilities. The rest should be hidden - that's why we call
it data hiding!

HTH,

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




More information about the Python-list mailing list