Re: Polymorphism the Python way

Discussion in 'Python' started by Peter Otten, Aug 31, 2003.

  1. Peter Otten

    Peter Otten Guest

    Daniel Klein wrote:

    > ...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.


    You can use properties, which simplifies the client code at the cost of an
    extra line in the class definition, e. g.:

    class Dead(object):
    def __init__(self, thing):
    self._thing = thing
    def getThing(self):
    return self._thing
    thing = property(getThing)

    class Parrot(Dead):
    def getThing(self):
    return self._thing + " with feathers"
    thing = property(getThing)


    dead = Dead("bird")
    parrot = Parrot("parrot")

    print dead.thing
    print parrot.thing
    Peter Otten, Aug 31, 2003
    #1
    1. Advertising

  2. Peter Otten

    Daniel Klein Guest

    On Sun, 31 Aug 2003 10:04:39 +0200, Peter Otten <>
    wrote:

    >Daniel Klein wrote:
    >
    >> ...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.

    >
    >You can use properties, which simplifies the client code at the cost of an
    >extra line in the class definition, e. g.:
    >

    Thanks. You and Alan Gauld provided the same answer, which seems to be
    the best approach.

    Dan
    Daniel Klein, Sep 2, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Michael Peuser

    Re: Polymorphism the Python way

    Michael Peuser, Aug 31, 2003, in forum: Python
    Replies:
    6
    Views:
    1,761
    Bob Gailer
    Sep 3, 2003
  2. Graham Fawcett

    Re: Polymorphism the Python way

    Graham Fawcett, Aug 31, 2003, in forum: Python
    Replies:
    1
    Views:
    318
    Daniel Klein
    Sep 2, 2003
  3. rashkatsa

    polymorphism in python

    rashkatsa, Nov 26, 2003, in forum: Python
    Replies:
    7
    Views:
    8,078
    Jay O'Connor
    Nov 26, 2003
  4. Krivenok Dmitry
    Replies:
    13
    Views:
    1,429
    Axter
    Jun 1, 2006
  5. Stephan Mueller
    Replies:
    7
    Views:
    626
    Stephan Mueller
    Aug 7, 2005
Loading...

Share This Page