Python: __dict__ class instance members are really dictionaries

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'}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.