object.attribute vs. object.getAttribute()

Jeff Epler jepler at unpythonic.net
Tue Sep 16 03:01:41 CEST 2003


On Mon, Sep 15, 2003 at 08:29:10PM -0400, Roy Smith wrote:
> 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.

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")
        
>>> from roy import C
>>> c = C()
>>> c.x = 3
>>> print c.x
9
>>> del c.x
>>> del c.x
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
>>> help(C)
[...]
 |   ----------------------------------------------------------------------
 |  Properties defined here:
 |  
 |  x
 |      A stupid attribute that squares itself... and won't go away
[...]

Jeff





More information about the Python-list mailing list