Python class instance members are really dictionaries/mappings. For example,
class Foo:
def __init__(self, name=''):
self.name = name
You can access the
name member:
In [2]: f = Foo('vito')
In [3]: f.name
Out[3]: 'vito'
You can also do:
In [4]: f.__dict__['name']
Out[4]: 'vito'
In fact, you can see all the data members:
In [5]: f.__dict__
Out[5]: {'name': 'vito'}
This gives us a quick way of creating an object at run time, say when parsing a text file. For a very contrived example, we have a text file that looks like this:
name=John,age=35,hobby=philately
name=Sally,age=28
name=Vito,age=18,sex=male
name=Maria,age=58
We can grab all the data into a bunch of objects like this:
class Person:
def __init__(self, name=''):
self.name = name
if __name__ == '__main__':
f = open('people.dat', 'ro')
people = []
for l in f.readlines():
people.append(Person())
lsp = l.strip().split(',')
p = []
for i in lsp:
p.append(i.split('='))
people[-1].__dict__ = dict(p)
for p in people:
print p.__dict__
And the output is:
{'hobby': 'philately', 'age': '35', 'name': 'John'}
{'age': '28', 'name': 'Sally'}
{'age': '18', 'name': 'Vito', 'sex': 'male'}
{'age': '58', 'name': 'Maria'}
You could do something fancier in
Person.__str__() (or the
__unicode__()) method:
def __str__(self):
retstr = ''
for k,v in self.__dict__.iteritems():
retstr += '%s: %s\n' % (k, v)
return retstr