Set/Get attribute syntatic sugar

Robert Kern rkern at ucsd.edu
Tue Jun 28 15:48:40 EDT 2005


Peter Hansen wrote:
> Заур Шибзухов wrote:
> 
>>There is a syntactic sugar for item access in
>>dictionaries and sequences:
>>
>>o[e] = v <-> o.__setitem__(e, v)
>>o[e] <-> o.__getitem__(e)
>>
>>where e is an expression.
>>
>>There is no similar way for set/get attribute for objects.
>>If e is a given name, then 
>>     
>>o.e = v <-> o.__setattr__(e, v)
>>o.e <-> o.__getattr__(e)
>>
>>Anybody thought about this issue?
> 
> Perhaps not, but now that you've pointed it out they've taken the time 
> machine back and fixed the problem before it arose:
> 
>  >>> class C:
> ...   def __setattr__(self, e, v):
> ...     print 'setting %s to %s' % (e, v)
> ...     self.__dict__[e] = v
> ...
>  >>> o = C()
>  >>> v = 'mystring'
>  >>> o.e = v
> setting e to mystring
>  >>> o.e
> 'mystring'
>  >>>

I think he means something like this:
e = 'i_am_an_attribute'
o.(e) = 10
o.i_am_an_attribute == 10

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list