Python 让对象能被转化为dict

# -*- coding: utf-8 -*-
class MyClass(object):
    """docstring for MyClass"""
    def __init__(self, attr1, attr2, attr3):
        self.attr1 = attr1
        self.attr2 = attr2
        self.attr3 = attr3

    def __iter__(self):
        attrs = dir(self)
        for attr in attrs:
            if attr.find('__') == 0:
                continue
            value = getattr(self, attr)
            if callable(value):
                continue
            yield (attr, value)
        


if __name__ == '__main__':
    obj = MyClass('gibbon', 'age', 30)

    print dict(obj)
    print list(obj)

 

posted on 2013-04-03 16:34  盐味  阅读(551)  评论(0编辑  收藏  举报