hasattr + __getattr__: I think this is Python bug
Ian Kelly
ian.g.kelly at gmail.com
Tue Jul 20 12:19:17 EDT 2010
On Tue, Jul 20, 2010 at 9:39 AM, dmitrey <dmitrey.kroshko at scipy.org> wrote:
>>How about using a property instead of the __getattr__() hook? A property is a computed attribute that (among other things) plays much nicer with hasattr.
>
> Could anyone provide an example of it to be implemented, taking into
> account that a user can manually set "myObject.size" to an integer
> value?
The following will work in Python 2.6+:
class MyClass(object):
@property
def size(self):
if not hasattr(self, '_size'):
self._size = self._compute_size()
return self._size
@size.setter
def size(self, value):
self._size = value
To support earlier versions of Python, you would write it like so:
class MyClass(object):
def _get_size(self):
if not hasattr(self, '_size'):
self._size = self._compute_size()
return self._size
def _set_size(self, value):
self._size = value
size = property(_get_size, _set_size)
More information about the Python-list
mailing list