object.attribute vs. object.getAttribute()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Roy Smith

    object.attribute vs. object.getAttribute()

    For the past 6-8 months, I've spent most of my time writing C++ and a
    little bit of Java. Both of these languages support and encourage the
    use of private data and explicit accessor functions, i.e. instead of
    writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
    writing Python, I find myself in a quandry.

    Historically, I've always avoided accessor functions and just reached
    directly into objects to get the value of their attributes. Since
    Python doesn't have private data, there really isn't much advantage to
    writing accessors, but somehow I'm now finding that it just feels wrong
    not to. I'm not sure if this feeling is just a C++/Java-ism that will
    cure itself with time, or if perhaps it really does make sense and I
    should change the way I code.

    On the plus side, accessors/mutators give me:

    1) Implicit documentation of which attributes I intended to be part of
    an object's externally visible state (accessors).
    2) Hooks to do data checking or invarient assertions (mutators).
    3) Decoupling classes by hiding the details of data structures.
    4) Vague feeling that I'm doing a good thing by being more in line with
    mainstream OO practices :-)

    On the minus side:

    1) More typing (which implies more reading, which I think reduces the
    readability of the finished product).
    2) Need to write (and test) all those silly little functions.
    3) Performance hit due to function call overhead.
    4) Only the appearance of private data (modulo some slots hackery).
    5) Code is harder to change (adding functionality means going back and
    adding more slots).
    6) Vague feeling that I'm dirtying myself by letting C++ and Java change
    my Python coding habits :-)

    Comments?
  • Michael Geary

    #2
    Re: object.attribut e vs. object.getAttri bute()

    I've always disliked accessor methods in C++ and Java. I can understand the
    reason for using them, but they are just so ugly.

    Danger: Advice from a Python newbie follows... :-)

    My suggestion would be to use Python properties, as defined with the
    property() function that was added in 2.2. Best of both worlds: You get the
    clean syntax of directly reading and writing properties just as if they were
    attributes, but behind the scenes you've defined get/set/del functions for
    each property.

    Personally, I wouldn't define properties for everything--I would use
    ordinary attributes wherever they do the job. The beauty is that you can
    always replace an attribute with a property without having to change the
    calling code--which eliminates most of the reason for using accessor methods
    as you would in C++.

    -Mike

    Roy Smith wrote:[color=blue]
    > For the past 6-8 months, I've spent most of my time writing C++ and a
    > little bit of Java. Both of these languages support and encourage the
    > use of private data and explicit accessor functions, i.e. instead of
    > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
    > writing Python, I find myself in a quandry.
    >
    > Historically, I've always avoided accessor functions and just reached
    > directly into objects to get the value of their attributes. Since
    > Python doesn't have private data, there really isn't much advantage to
    > writing accessors, but somehow I'm now finding that it just feels wrong
    > not to. I'm not sure if this feeling is just a C++/Java-ism that will
    > cure itself with time, or if perhaps it really does make sense and I
    > should change the way I code.
    >
    > On the plus side, accessors/mutators give me:
    >
    > 1) Implicit documentation of which attributes I intended to be part of
    > an object's externally visible state (accessors).
    > 2) Hooks to do data checking or invarient assertions (mutators).
    > 3) Decoupling classes by hiding the details of data structures.
    > 4) Vague feeling that I'm doing a good thing by being more in line with
    > mainstream OO practices :-)
    >
    > On the minus side:
    >
    > 1) More typing (which implies more reading, which I think reduces the
    > readability of the finished product).
    > 2) Need to write (and test) all those silly little functions.
    > 3) Performance hit due to function call overhead.
    > 4) Only the appearance of private data (modulo some slots hackery).
    > 5) Code is harder to change (adding functionality means going back and
    > adding more slots).
    > 6) Vague feeling that I'm dirtying myself by letting C++ and Java change
    > my Python coding habits :-)
    >
    > Comments?[/color]


    Comment

    • Jeff Epler

      #3
      Re: object.attribut e vs. object.getAttri bute()

      On Mon, Sep 15, 2003 at 08:29:10PM -0400, Roy Smith wrote:[color=blue]
      > For the past 6-8 months, I've spent most of my time writing C++ and a
      > little bit of Java. Both of these languages support and encourage the
      > use of private data and explicit accessor functions, i.e. instead of
      > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
      > writing Python, I find myself in a quandry.
      >
      > Historically, I've always avoided accessor functions and just reached
      > directly into objects to get the value of their attributes. Since
      > Python doesn't have private data, there really isn't much advantage to
      > writing accessors, but somehow I'm now finding that it just feels wrong
      > not to. I'm not sure if this feeling is just a C++/Java-ism that will
      > cure itself with time, or if perhaps it really does make sense and I
      > should change the way I code.[/color]

      Write your python code naturally, using 'x = foo.bar'. Derive all your
      classes from 'object' (use new-style classes). If you ever need
      to do something "behind the scenes", you can switch to using "property",
      and have a function automatically called on attribute read, write, and
      delete---and it even documents itself:

      class C(object):
      def __init__(self):
      self._y = 0

      def get_x(self):
      return self._y * self._y

      def set_x(self, val):
      self._y = val

      def del_x(self):
      raise TypeError, "Cannot delete attribute"

      x = property(get_x, set_x, del_x,
      "A stupid attribute that squares itself"
      "... and won't go away")
      [color=blue][color=green][color=darkred]
      >>> from roy import C
      >>> c = C()
      >>> c.x = 3
      >>> print c.x[/color][/color][/color]
      9[color=blue][color=green][color=darkred]
      >>> del c.x
      >>> del c.x[/color][/color][/color]
      Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "/tmp/roy.py", line 12, in del_x
      raise TypeError, "Cannot delete attribute"
      TypeError: Cannot delete attribute[color=blue][color=green][color=darkred]
      >>> help(C)[/color][/color][/color]
      [...]
      | ----------------------------------------------------------------------
      | Properties defined here:
      |
      | x
      | A stupid attribute that squares itself... and won't go away
      [...]

      Jeff

      Comment

      • Lulu of the Lotus-Eaters

        #4
        Re: object.attribut e vs. object.getAttri bute()

        Roy Smith <roy@panix.co m> wrote previously:
        |1) Implicit documentation of which attributes I intended to be part of
        |an object's externally visible state (accessors).

        Some attribute names start with an underscore. Those are the ones that
        are NOT intended to be part of the external interface.

        |2) Hooks to do data checking or invarient assertions (mutators).

        Yep, you need accessors (or properties) to do this.

        |3) Decoupling classes by hiding the details of data structures.

        Initial underscores again.

        |4) Vague feeling that I'm doing a good thing by being more in line with
        |mainstream OO practices :-)

        If you want to be mainstream, use VB. But accessors are not IMO a
        requirement for "proper" OOP.

        Yours, Lulu...

        --
        _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/
        _/_/ ~~~~~~~~~~~~~~~ ~~~~~[mertz@gnosis.cx]~~~~~~~~~~~~~~~ ~~~~~~ _/_/
        _/_/ The opinions expressed here must be those of my employer... _/_/
        _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them! _/_/


        Comment

        • John Roth

          #5
          Re: object.attribut e vs. object.getAttri bute()


          "Roy Smith" <roy@panix.co m> wrote in message
          news:roy-81B3E5.20291015 092003@reader2. panix.com...[color=blue]
          > For the past 6-8 months, I've spent most of my time writing C++ and a
          > little bit of Java. Both of these languages support and encourage the
          > use of private data and explicit accessor functions, i.e. instead of
          > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
          > writing Python, I find myself in a quandry.
          >
          > Historically, I've always avoided accessor functions and just reached
          > directly into objects to get the value of their attributes. Since
          > Python doesn't have private data, there really isn't much advantage to
          > writing accessors, but somehow I'm now finding that it just feels wrong
          > not to. I'm not sure if this feeling is just a C++/Java-ism that will
          > cure itself with time, or if perhaps it really does make sense and I
          > should change the way I code.[/color]

          I'm with Jeff on this one. If it looks like a value, then access it
          directly.
          If you need to slide a mutator in under it, it's simple enough to make
          it a property later without affecting any of the code that uses it.

          [color=blue]
          > On the plus side, accessors/mutators give me:
          >
          > 1) Implicit documentation of which attributes I intended to be part of
          > an object's externally visible state (accessors).[/color]

          Use the underscore convention.
          [color=blue]
          > 2) Hooks to do data checking or invarient assertions (mutators).
          > 3) Decoupling classes by hiding the details of data structures.
          > 4) Vague feeling that I'm doing a good thing by being more in line with
          > mainstream OO practices :-)[/color]

          4 is actually the same thing as 3, except not stated as cleanly.
          [color=blue]
          > On the minus side:
          >
          > 1) More typing (which implies more reading, which I think reduces the
          > readability of the finished product).
          > 2) Need to write (and test) all those silly little functions.
          > 3) Performance hit due to function call overhead.
          > 4) Only the appearance of private data (modulo some slots hackery).
          > 5) Code is harder to change (adding functionality means going back and
          > adding more slots).
          > 6) Vague feeling that I'm dirtying myself by letting C++ and Java change
          > my Python coding habits :-)[/color]

          Items 1 through 3 don't matter if you use properties. You use them when
          you need them, otherwise you simply access the attribute directly.

          If you're using Python, you don't worry about private data. Use the
          underscore convention, and don't worry otherwise.

          Don't use slots.

          I never worry about where a good idea comes from.

          John Roth[color=blue]
          >
          > Comments?[/color]


          Comment

          • Troy Melhase

            #6
            Re: object.attribut e vs. object.getAttri bute()

            Hi Roy:
            [color=blue]
            > I'm not sure if this feeling is just a C++/Java-ism that will
            > cure itself with time, or if perhaps it really does make sense and I
            > should change the way I code.[/color]

            If you're not sure, I suggest you err on the side of caution. To me caution
            means writting less code, not more. And this isn't really an either-or
            proposition. One of the best things about properties is that clients can't
            easily distinguish them from normal attribute access. Nothing stops you
            from starting with simple attributes and then later changing them to
            properties later.
            [color=blue]
            > 6) Vague feeling that I'm dirtying myself by letting C++ and Java change
            > my Python coding habits :-)[/color]

            This need not be vague. I have that feeling concretely when thinking of
            Java.

            -troy

            Comment

            • Aurelio Martin Massoni

              #7
              Re: object.attribut e vs. object.getAttri bute()


              Read this nice article "Why getter and setter methods are evil: Make
              your code more maintainable by avoiding accessors"

              Business technology, IT news, product reviews and enterprise IT strategies.




              "Roy Smith" <roy@panix.co m> escribió en el mensaje
              news:roy-81B3E5.20291015 092003@reader2. panix.com...[color=blue]
              > For the past 6-8 months, I've spent most of my time writing C++ and a
              > little bit of Java. Both of these languages support and encourage the
              > use of private data and explicit accessor functions, i.e. instead of
              > writing x = foo.bar, you write x = foo.getBar(). Now that I'm back to
              > writing Python, I find myself in a quandry.
              >
              > Historically, I've always avoided accessor functions and just reached
              > directly into objects to get the value of their attributes. Since
              > Python doesn't have private data, there really isn't much advantage to
              > writing accessors, but somehow I'm now finding that it just feels[/color]
              wrong[color=blue]
              > not to. I'm not sure if this feeling is just a C++/Java-ism that will
              > cure itself with time, or if perhaps it really does make sense and I
              > should change the way I code.
              >
              > On the plus side, accessors/mutators give me:
              >
              > 1) Implicit documentation of which attributes I intended to be part of
              > an object's externally visible state (accessors).
              > 2) Hooks to do data checking or invarient assertions (mutators).
              > 3) Decoupling classes by hiding the details of data structures.
              > 4) Vague feeling that I'm doing a good thing by being more in line[/color]
              with[color=blue]
              > mainstream OO practices :-)
              >
              > On the minus side:
              >
              > 1) More typing (which implies more reading, which I think reduces the
              > readability of the finished product).
              > 2) Need to write (and test) all those silly little functions.
              > 3) Performance hit due to function call overhead.
              > 4) Only the appearance of private data (modulo some slots hackery).
              > 5) Code is harder to change (adding functionality means going back and
              > adding more slots).
              > 6) Vague feeling that I'm dirtying myself by letting C++ and Java[/color]
              change[color=blue]
              > my Python coding habits :-)
              >
              > Comments?[/color]


              Comment

              • Sean Ross

                #8
                Re: object.attribut e vs. object.getAttri bute()

                Hi.

                "Roy Smith" <roy@panix.co m> wrote in message
                news:roy-81B3E5.20291015 092003@reader2. panix.com...
                [snip][color=blue]
                > 1) More typing (which implies more reading, which I think reduces the
                > readability of the finished product).
                > 2) Need to write (and test) all those silly little functions.[/color]

                If you only intend to create simple properties[*], then the following recipe
                may address issues 1) and 2) (except for the testing part):



                If you're going to create more complex properties, you may find this
                recipe(idiom) of interest:




                Hope that's useful,
                Sean


                [*] By "simple properties", I mean something like the following:

                ''' assume we're inside a class definition
                and self.__foo has been initialized.
                '''
                def get_foo(self):
                return self.__foo
                def set_foo(self, value):
                self.__foo = value
                def del_foo(self):
                del self.__foo
                foo = property(fget=g et_foo, fset=set_foo, fdel=del_foo, doc="foo")





                Comment

                • Michael Geary

                  #9
                  Re: object.attribut e vs. object.getAttri bute()

                  Aurelio Martin Massoni wrote:[color=blue]
                  > Read this nice article "Why getter and setter methods are evil: Make
                  > your code more maintainable by avoiding accessors"
                  >
                  > http://www.javaworld.com/javaworld/j...5-toolbox.html[/color]

                  That's an interesting article. Be sure to read the comments at the end of
                  page 3--the real fun starts there!

                  -Mike


                  Comment

                  Working...