property () for Java Programmers ?
Steven Bethard
steven.bethard at gmail.com
Wed Jan 12 12:42:06 EST 2005
michael wrote:
> Hi there,
>
> I am somewhat confused by the following :
>
> class C(object):
> def getx(self): return self.__x
> def setx(self, value): self.__x = "extended" + value
> def delx(self): del self.__x
> x = property(getx, setx, delx, "I'm the 'x' property.")
>
> So far so good :-) But what to do with this now
>
>
>>>>c = C
>>>>c
>
> <class '__main__.C'>
>
>>>>dir (c)
>
> ['__class__', '__delattr__', '__dict__', '__doc__',
> '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
> '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
> '__weakref__', 'delx', 'getx', 'setx', 'x']
>
>>>>c.x
>
> <property object at 0x401edbbc>
>
>
> ?????? What can I do with this "property object" now.
Well, if you actually want your getx/setx/delx to be called, then you
need an *instance* of class C:
py> c = C()
py> c.x
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 2, in getx
AttributeError: 'C' object has no attribute '_C__x'
py> c.x = "42"
py> c.x
'extended42'
py> del c.x
py> c.x
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 2, in getx
AttributeError: 'C' object has no attribute '_C__x'
Note that I used 'c = C()' instead of 'c = C' as in your code.
STeve
More information about the Python-list
mailing list