Mix-in 类
一种小型的类 它只定义其它类可能需要提供的一套附加方法 而不定义自己的类实例属性。此外 它也不要求使用者调用自己的 __init__ 构造器。 避免多继承问题
class ToDictMixin:
把内存中的 python 对象转换为字典形式 以便将其序列化。
def to_dict(self):
return self._traverse_dict(self.__dict__)
def _traverse_dict(self, instance_dict):
ouput {}
for key, value in instance_dict.items():
ouput[key] self._traverse(key, value)
return ouput
def _traverse(self, key, value):
if isinstance(value, ToDictMixin):
return value.to_dict()
elif isinstance(value, dict):
return self._traverse_dict(value)
elif isinstance(value, list):
return [self._traverse(key, i) for i in value]
elif hasattr(value, __dict__ ):
return self._traverse_dict(value.__dict__)
else:
return value
class BinaryTree(ToDictMixin):
def __init__(self, value, left None, right None):
self.value value
self.left left
self.right right
self._dict { a : 1, b : 2}
self._list [1, 2]