I am trying to figure out if there is an implicit way to iterate through list elements. Example: with the list someList = ['a','b','c']
you do not need to write a for
loop to iterate through the list printing elements when print(someList)
does an implicit iteration.
I have the following (simplified) python code:
class foo:
def __init__(self):
self.x=None
self.y=None
self.z=None
def set(self, x, y , z):
self.x = x
self.y = y
self.z = z
def get(self):
return {'x':self.x, 'y':self.y, 'z':self.z}
class bar:
def __init__(self):
self.foos=[]
def add(self, foo):
self.foos.append(foo)
def get(self):
return {'foos':self.foos}
Which are initialized using
f = foo()
f.set(1,2,3)
g = foo()
g.set(4,5,6)
h = bar()
h.add(f)
h.add(g)
Then calling
print(f.get())
print(g.get())
print(h.get())
which gives
{'z': 3, 'x': 1, 'y': 2}
{'z': 6, 'x': 4, 'y': 5}
{'foos': [<__main__.foo object at 0x0000000003541748>, <__main__.foo object at 0x000000000358C630>]}
What I'm ultimately looking to do is return a JSON like structure or Nested dictionary such that the returns of the foo.get()
method are included in the call to bar.get()
.
I realize the array doesn't contain actual foo
objects (only references to them).
I thought about using iterators like they were explained at http://anandology.com/python-practice-book/iterators.html . The problem with the example is that the items to be iterated over must be defined within the datastructure (i.e foo
). The problem with including the iterator in the bar
class is that foos
list may not be the only collection to iterate over: I could have added collection foos2
(but did not for simplicity)
I considered the solution at Access nested dictionary items via a list of keys? , but the pprint
gives me something similar to my own code. I am also not certain use of the reduce
function would apply to my situation.
I also thought about doing operator overloading on the print
function, but I'm not looking to get a string, just a data structure that easy to display but also navigate.
Is there a easy way or correct way to do this? Am I using the correct data-structure (i.e. should I be using something other than nested lists)?
I'm still new to Python so pleas be gentle.