question on __dict__

Thomas Jensen thomasNO at SPAM.obscure.dk
Thu Nov 22 13:23:19 CET 2001


Markus Jais <mjais at web.de> wrote in 
news:pan.2001.11.22.12.52.34.97867.2869 at web.de:

> hello
> can somebody tell me, what the difference is between
> 
> self.__dict__('foo') = 'bar'

You mean self.__dict__['foo'] = 'bar' right ?

> and
> self.foo = 'bar'
> 
> or is there no difference?

In most cases there is no difference (except I suspect the former is 
somwhat slower).
All Python objects has an attribute __dict__ which contains the 
object's attributes. When assigning to 'foo' you are actually refering 
to the 'foo' key of the object's __dict__ dictionary.
It is possible to override this behaviour by defining the method 
__setattr__ in the class in which case differences might occur.
  http://www.python.org/doc/current/ref/attribute-access.html
Generally, I don't think you should access __dict__ unless you have a 
specific reason.
If you need to get 'foo' from a string, have a look at setattr().
  http://www.python.org/doc/current/lib/built-in-funcs.html

-- 
Best Regards
Thomas Jensen



More information about the Python-list mailing list