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)
原文地址:https://www.cnblogs.com/gibbon/p/2998190.html