Created
April 14, 2016 06:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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