setting a property via self.__dict__
Bengt Richter
bokr at oz.net
Wed Oct 30 21:25:19 EST 2002
On 30 Oct 2002 12:51:47 -0800, fvondelft at syrrx.com (Frank von Delft) wrote:
>Duncan Booth <duncan at rcp.co.uk> wrote in message news:<Xns92B75C6BDF4Eduncanrcpcouk at rcp.co.uk>...
>
>> The property is an entry in the class's dictionary, not in the instance.
>
>
>Um... after some mulling: so what is the advantage of having the
>property in the class dictionary? Because I realised it's quite happy
>in the instance dictionary, like such:
>
>>>> class A(object):
> def __init__(self,**kwargs):
> self.a = property(self._getA,self._setA)
> self.__dict__.update(**kwargs)
> def _getA(self):
> return self._a
> def _setA(self,a):
> self._a = a
>
>Really I should ask: why do all the examples show it defined in the
>class dictionary?
>
Why don't you try your code and see how it behaves?
>>> class A(object):
... def __init__(self,**kwargs):
... self.a = property(self._getA, self._setA)
... self.__dict__.update(**kwargs)
... def _getA(self):
... return self._a
... def _setA(self,a):
... self._a = a
...
>>> a=A(x=1,y='two')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __init__
TypeError: update() takes no keyword arguments
Ok, minor typo, to give you the benefit.
>>> class A(object):
... def __init__(self,**kwargs):
... self.a = property(self._getA, self._setA)
... self.__dict__.update(kwargs)
... def _getA(self):
... return self._a
... def _setA(self,a):
... self._a = a
...
>>> a=A(x=1,y='two')
>>> vars(a)
{'a': <property object at 0x007F51A0>, 'y': 'two', 'x': 1}
>>> a.a
<property object at 0x007F51A0>
Did you expect to trigger _getA there?
You probably didn't try this?
Regards,
Bengt Richter
More information about the Python-list
mailing list