"properties" idiom

Mike C. Fletcher mcfletch at rogers.com
Thu Nov 21 01:35:45 EST 2002


Yes, there is such an API, but it really only becomes full-fledged with 
Python 2.2.2 (where it is called the "descriptors" API).  You can read 
all about it in Guido's Python 2.2.x introduction.

http://www.python.org/2.2.2/descrintro.html

You can use the standard self.x stuff until you need properties, then 
switch to properties when you need them.  My own basicproperty project 
extends the concept somewhat, but it doesn't sound like you need that.

Enjoy,
Mike

Terry Hancock wrote:

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

-- 
_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/







More information about the Python-list mailing list