Skip to content

Instantly share code, notes, and snippets.

@giwa
Created April 14, 2016 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giwa/0dcd815bfaf026dd3dffb9fd15a7318e to your computer and use it in GitHub Desktop.
Save giwa/0dcd815bfaf026dd3dffb9fd15a7318e to your computer and use it in GitHub Desktop.
EP 26 Use Multiple Inheritance Only for Mix-in Utility Classes ref: http://qiita.com/giwa/items/a3a92b56049b84b9965a
import time
class ToDictMixin:
def to_dict(self):
return self._traverse_dict(self.__dict__)
def _traverse_dict(self, instance_dict):
output = {}
for key, value in instance_dict.items():
output[key] = self._traverse(key, value)
return output
def _traverse(self, key, value):
time.sleep(0.2)
if isinstance(value, ToDictMixin):
print('ToDictMixin')
return value.to_dict()
elif isinstance(value, dict):
print('dict')
return self._traverse_dict(value)
elif isinstance(value, list):
print('list')
return [self._traverse(key, i) for i in value]
elif hasattr(value, '__dict__'):
print('hasattr __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
tree = BinaryTree(10, left=BinaryTree(7, right=BinaryTree(9)),
right=BinaryTree(13, left=BinaryTree(11)))
# print(tree.to_dict())
class BinaryTreeWithParent(BinaryTree):
def __init__(self, value, left=None, right=None, parent=None):
super().__init__(value, left=left, right=right)
self.parent = parent
def _traverse(self, key, value):
if (isinstance(value, BinaryTreeWithParent) and key == 'parent'):
return value.value
else:
return super()._traverse(key, value)
root = BinaryTreeWithParent(10)
root.left = BinaryTreeWithParent(7, parent=root)
root.left.right = BinaryTreeWithParent(9, parent=root.left)
print(root.to_dict())
class NamedSubTree(ToDictMixin):
def __init__(self, name, tree_with_parent):
self.name = name
self.tree_with_parent = tree_with_parent
my_tree = NamedSubTree('foobar', root)
print(my_tree.to_dict())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment