Search code examples
pythonstringtreeattributesglobal

how to access attributes using globals() in python


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.


Solution

  • 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)