I’m new here and pretty new to python!
We got a homework, and I already was able to do rest of it, but one problem remains:
If I have a tree hierarchy like this:
root = [
parent1 = [
child1,
child2 = [
sub_child
]
child3
],
parent2 = [
child1,
child2
]
]
And they are all instances of one class named TreeHierarchyClass, and they all have a name attribute, how can I find the one with name I input?
I tried to use for loops but there’s no way to know how many I need? Getting the name is easy:
name = input("Enter name: ")
if name == TreeHierarchyObject.name:
print("Found it!")
but how do I loop through the objects?
You should use simple recursion here.
The method depends a little on how your child objects are attached to the parent object.
This one works if they are in a list
self.children, which I’d recommend to do.Just define the following method inside your class:
Edit:
To make this work for any attribute, not just name, use
getattr()instead:And simply call
root.findObjectByName("Sub Child!")or to use the second method:root.findObject("name", "Sub Child!")