[Tutor] Initialize Class Variables by Dictionary ...

Mac Ryan quasipedia at gmail.com
Sat Aug 29 22:59:20 CEST 2009


On Sat, 2009-08-29 at 16:31 -0400, Damon Timm wrote:
> Hi again - thanks for your help with my question early today (and last
> night).  Tried searching google for this next question but can't get
> an answer ... here is what I would like to do (but it is not working)
> ...
> 
> >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'}
> >>> class Test():
> ...   def __init__(self):
> ...     for key in dict:
> ...       self.key = dict[key]
> ...
> >>> t = Test()
> >>> t.test1
> Traceback (most recent call last):
>   File "<console>", line 1, in <module>
> AttributeError: Test instance has no attribute 'test1'
> >>> t.key
> 'value3'
> 
> Can I do what I am dreaming of ?

Yes you can, but not that way. Here is how I did on my console:

>>> class A(object):
...   pass
... 
>>> dir(A)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__']
>>> setattr(A, 'test1', 'mytest')
>>> dir(A)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'test1']
>>> A.test1
'mytest'

So, the key here is to use the setattr() builtin function.

However keep in mind that I am a python beginner, so you would probably
like to hear from some real tutors before implementing this solution all
over your code...

Mac.




More information about the Tutor mailing list