One-Shot Property?

Terry Hancock hancock at anansispaceworks.com
Fri Jan 28 16:35:02 CET 2005


On Tuesday 18 January 2005 12:33 pm, John Lenton wrote:
> 
> consider this:
> 
>    1 >>> class C:
>    2 ...     x = property(str)
>    3 ... 
>    4 >>> c = C()
>    5 >>> c.x
>    6 '<__main__.C instance at 0x4008d92c>'
>    7 >>> setattr(c, 'x', c.x)
>    8 >>> c.x
>    9 '<__main__.C instance at 0x4008d92c>'
>   10 >>> C.x
>   11 <property object at 0x4009a7ac>
>   12 >>> c.x = 2
>   13 >>> 
> 
> in line 5 you see that the x property so defined works. In line 7 you
> remove it, replacing it with the computed value of the property. Line
> 9 shows that it worked, line 11 shows that it didn't break the class,
> and line 13 (through the absence of an exception) shows that it no
> longer is 'special' (as it shouldn't be).

It wasn't "special" before, either -- I tried this myself, because I wasn't
familiar with properties yet, and I was trying to figure out what you
meant by that.

The catch is that I think you meant to type:

>    1 >>> class C(object):

(i.e. so that C is a "new-style" class).

Then we get "special" behavior (which answers my first question):

>>> class C(object):
...     x = property(str)
...
>>> C.x
<property object at 0x401e8cd4>
>>> c = C()
>>> c.x
'<__main__.C object at 0x401e984c>'
>>> c.x = 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: can't set attribute
>>>

Unfortunately this seems to break your technique, too:

>>> setattr(c, 'x', c.x)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: can't set attribute

Too bad.  I was kind of hoping it was just a typo. :-(

Unless I'm missing something, anyway.

Cheers,
Terry

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




More information about the Python-list mailing list