indexed property? Can it be done?

Chris Angelico rosuav at gmail.com
Tue May 8 02:01:00 EDT 2012


On Tue, May 8, 2012 at 2:18 PM, Charles Hixson
<charleshixsn at earthlink.net> wrote:
> Not as clean as what I'm hoping for, but so far I haven't come up with any
> way except functions that doesn't directly expose the data...and if I must
> use that approach, then the class doesn't buy me anything for the overhead.)

C++ and Java teach us to hide everything and use trivial getters and
setters to make things available:

class Foo
{
private:
    int value;
public:
    int getValue() {return value;}
    int setValue(int newval) {return value=newval;}
};

Python lets us happily access members directly, but change to
getter/setter if we need to: (example lifted from
http://docs.python.org/library/functions.html#property )

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

Not fundamentally different, except that with Python, you can skip all
this in the simple case:

class C(object):
    def __init__(self,val):
        self.value = val

In short, data hiding isn't such a great thing after all. Just use the
members directly until such time as you find you need to change that
(and be honest, how often have you had thin getter/setter methods and
then changed their functionality?).

ChrisA



More information about the Python-list mailing list