[Tutor] new object attribute from string?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun Apr 13 21:34:01 2003

> > Is it possible to make a new object attribute or blank dictionary from
> > the value of a string?
> You can even wrap the whole thing in syntax-sugar via classes. Something
> like this should be enough (Python > 2.2)
> class callable_dict(dict):
>     def __call__(self, key, *args, **kwargs):
>         return self[key](*args, **kwargs)


It is possible to dynamically add new attributes to our objects.  Each
object in Python has an internal '__dict__' dictionary that keeps track of
all of its attributes:

>>> class TestAttribute:
...     def __init__(self, name):
...         self.name = name
...     def printInternals(self):
...         print "my dictionary looks like this:", self.__dict__
>>> t1 = TestAttribute('Chris')
>>> t1.printInternals()
my dictionary looks like this: {'name': 'Chris'}

And we're already very familiar with dictionaries: we can easily add new
attributes by assigning another key to that __dict__ionary.

>>> t1.__dict__['question'] = 'new object attribute from string?'
>>> t1.question
'new object attribute from string?'
>>> t1.printInternals()
my dictionary looks like this: {'question':
                                    'new object attribute from string?',
                                'name': 'Chris'}

Hope this helps!