A method to convert python object to dict(supporting recursion)

Table of contents

Code

def object2Map(obj:object):
    """covert object to dict"""
    m = obj.__dict__
    for k in m.keys():
        v = m[k]
        if hasattr(v, "__dict__"):
            m[k] = object2Map(v)
    return m

Test

class Test:
    def __init__(self):
        self.a = 1
        self.b = 2

test = Test()
test.c = Test()
print(object2Map(test))

results: result pitcture