Created
March 25, 2014 20:26
-
-
Save atomictom/9770608 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# Recursive descent wrapper for objects containing objects | |
import functools | |
def recursive_descent(fn): | |
@functools.wraps(fn) | |
def wrapped(self, *args, **kwargs): | |
fn(self, *args, **kwargs) | |
# Could dynamically pick the name of the 'objects' list | |
# by doing self.__dict__(name)... | |
for obj in self.objects: | |
wrapped(obj, *args, **kwargs) | |
return wrapped | |
class Test(object): | |
def __init__(self, name, children): | |
self.name = name | |
self.objects = children | |
@recursive_descent | |
def display(self, mes): | |
print self.name + " says: " + mes | |
# Two levels of children under root | |
root = Test("root", [Test("Child {}".format(i), [Test("Grandchild {}".format(j), []) for j in range(10)]) for i in range(10)]) | |
# A third level for just one grandchild | |
root.objects[-1].objects[-1].objects = [Test("GREATGRANDCHILD", [])] | |
# Recursively descend | |
root.display('hi!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment