Mixing custom __setattr__ method and properties in new style classes
Scott David Daniels
scott.daniels at acm.org
Wed Feb 8 12:35:49 EST 2006
L.C. Rees wrote:
> Can custom __setattr__ methods and properties be mixed in new style
> classes?
>
> I experimented with a new style class with both a custom __setattr__
> method and a property. Attributes controlled by the __setattr__ method
> work fine. When I attempt to set or get the property it raises the
> error: "TypeError: _settext() takes exactly two arguments (1 given)".
> This suggests that the __setattr__ may be conflicting with assignment
> to the property since it doesn't seem the class name is being passed to
> the property when it's created. This is the code for the property at
> the end of the class definition:
>
> def _settext(self, txt):
> self._tree.text = txt
>
> def _gettext(self, txt):
> return self._tree.text
>
> def _deltext(self, txt):
> self._tree.text = ''
>
> text = property(_settext, _gettext, _deltext)
>
The order to call property is get, set, del, doc
You need to take a _lot_ more care before asking for help.
neither get not del take any arg besides self. When you are
trying to debug an interaction, make sure your tests work stand-
alone.
class Holder(object): pass # to allow attributes stuck on
class Demo(object):
def __init__(self):
self._tree = Holder()
def _settext(self, txt):
self._tree.text = txt
def _gettext(self):
return self._tree.text
def _deltext(self):
self._tree.text = ''
text = property(_gettext, _settext, _deltext, 'text property')
d = Demo()
d.text = 'my text'
print repr(d.text)
del d.text
print repr(d.text)
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list