"properties" idiom

Terry Hancock hancock at anansispaceworks.com
Thu Nov 21 01:19:43 EST 2002


I could swear I saw a conversation about this on list, but I'm having
trouble finding anything relevant.

Let's say I have a class that exposes an attribute  x as part of it's public
API:

class spam:
    def __init__(self, x):
        self.x = x

Due to later development, however, it's clear (hypothetically)
that setting or getting the value of x, requires a method call
(to update a database, for example).

Is there a standard idiom for calling that method when an outside
caller does something like:

spaminstance.x = 42

or

y = spaminstance.x

(i.e. when we see this, my class actually calls an internal method,
spaminstance.__set_x(42)).  If so, I'd have the same flexibility as if I
had used get_x()/set_x() accessor methods, but my code would
be simpler for the most common case.  Can you do this with Python
today?  I was thinking there might be a way using __getattr__ and
__setattr__, but it initially looks very complex -- is there a preferred
way to do it?

I'm defining an interface now, and I'm wondering whether I should
go with attributes or accessor-methods.  I've been using accessor
methods, but it bloats the interface quite a bit, and I'm wondering if I
can make the interface simpler this way.

Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list