0

I wanna access one of attributes of some of my tree nodes and their name is like "image1,imag2,..." so I found globals cool to avoid writing duplicated codes; but using globals i couldn't access attributes; i new to python so yup I'm newbie.

this is my code:

Image1=Node("I1",path="path",parent=Images,priceL=prices[0:12],fp=np.array([70,172]))

print(globals()["Image"+str(image)+".path"])

there is errors:

 print(globals()["Image"+str(image)+".path"])
        ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'Image1.path'

i tried: print(globals()[f"Image{str(image)}.path"]) and storing the globals outcome in an other variable but its not how it works.

  • 2
    Not a direct answer to your question, but have you considered to use ``dict`` instead of (ab)using ``globals()``? See: https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables. And if ``globals()["Image"+str(image)]`` gives you the object you're looking for, then ``(globals()["Image"+str(image)]).path`` should give you the attribute you're looking for. – Mike Scotty Mar 12 '23 at 07:31
  • thanks dude it worked. idk why i didnt used dict but it may be more clever and cleaner. –  Mar 12 '23 at 07:38

1 Answers1

0

Step:1 ==> First retrieve the node object from globals()

Step:2 ==> Use getattr() function to access the attribute of the node.

Image1 = Node("I1", path="path", parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
node = globals()["Image" + str(image)] 
path = getattr(node, "path") 
print(path)
Iqbal Hussain
  • 1,077
  • 1
  • 4
  • 12