在我的web應用程序中,我經常需要將對象序列化爲JSON。 並非所有對象都默認JSON序列化的,所以我用我自己的encode_complex
方法,它傳遞給simplejson.dumps
如下:simplejson.dumps(context, default=self.encode_complex)
可以自己寫魔法嗎?
是否還好定義自己的魔術方法稱爲__json__(self)
,然後使用類似的代碼在encode_complex
方法下面?
def encode_complex(self, obj):
# additional code
# encode using __json__ method
try:
return obj.__json__()
except AttributeError:
pass
# additional code
+1在這裏,因爲你的問題使我知道名稱修改不會發生在也以*兩個下劃線*結尾的方法上。並不是說我會用它來創建新的魔法方法。 – 2012-07-06 17:33:27