Set/Get attribute syntatic sugar

Peter Hansen peter at engcorp.com
Tue Jun 28 14:48:26 EDT 2005


Заур Шибзухов 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'
 >>>

-Peter



More information about the Python-list mailing list