在python中,如何将类对象转换为字典
比方说,我已经有了一个简单的Python类
class Wharrgarbl(object): def __init__(self, a, b, c, sum, version='old'): self.a = a self.b = b self.c = c self.sum = 6 self.version = version def __int__(self): return self.sum + 9000 def __what_goes_here__(self): return {'a': self.a, 'b': self.b, 'c': self.c}
我可以很容易地把它转换成一个整数
>>> w = Wharrgarbl('one', 'two', 'three', 6) >>> int(w) 9006
太棒了! 但是,现在我想用类似的方式把它写成字典
>>> w = Wharrgarbl('one', 'two', 'three', 6) >>> dict(w) {'a': 'one', 'c': 'three', 'b': 'two'}
我需要什么来定义这个工作? 我试着用__dict__和dict代替__what_goes_here__ ,但是dict(w)导致了TypeError: Wharrgarbl object is not iterable在两种情况下TypeError: Wharrgarbl object is not iter