假设我在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}
Run Code Online (Sandbox Code Playgroud)
我可以很容易地将它转换为整数
>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> int(w)
9006
Run Code Online (Sandbox Code Playgroud)
哪个好极了!但是,现在我想以类似的方式把它变成一个字典
>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}
Run Code Online (Sandbox Code Playgroud)
我需要为此定义什么?我试图取代这两个__dict__和dict的__what_goes_here__,但dict(w)导致了TypeError: Wharrgarbl object is …