Polymorphism the Python way

Graham Fawcett fawcett at teksavvy.com
Sun Aug 31 09:47:49 CEST 2003

Daniel Klein wrote:

>Given the following code,,,
>class Dead(object):
>    def __init__(self, adeadthing):
>        self.deadthing = adeadthing
>    def getthing(self):
>        return self.deadthing
>class Parrot(object):
>    def __init__(self, aparrotthing):
>        self.parrotthing = aparrotthing
>    def getthing(self):
>        return self.parrotthing
>...and then somewhere in some script I use...
>    self.getthing()
>to get whatever 'thing' I want to get.
>Isn't there a better way to do this in Python? I hate doing these
>'get' type methods. The seem ugly to me.
>Daniel Klein

Why not just use the same attribute name in each class?

    class Dead(object):
        def __init__(self, deadthing):
            self.thing = deadthing

    class Parrot(object):
        def __init__(self, parrotthing):
            self.thing = parrotthing

Then you can access the attribute as `someobj.thing`.

Given that you hate getters, and that you didn't title your message, 
"Encapsulation the Python Way", accessing instance attributes directly 
is fair game.  ;-)

-- Graham

More information about the Python-list mailing list