英文:
how to access attributes using globals() in python
问题
我想访问一些树节点的属性之一,它们的名称类似于“image1、image2,...”,所以我发现全局变量很酷,可以避免编写重复的代码;但是使用全局变量,我无法访问属性;我是 Python 新手,所以是的,我是新手。
这是我的代码:
```python
Image1=Node("I1", path="path", parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
print(globals()["Image"+str(image)+".path"])
出现了错误:
print(globals()["Image"+str(image)+".path"])
~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'Image1.path'
我尝试过:
print(globals()[f"Image{str(image)}.path"])
并将全局变量的结果存储在另一个变量中,但这不是它的工作方式。
<details>
<summary>英文:</summary>
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.
</details>
# 答案1
**得分**: 0
步骤1 ==> 首先从全局变量中检索节点对象。
步骤2 ==> 使用getattr()函数访问节点的属性。
Image1 = Node("I1", path="路径", parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
node = globals()["Image" + str(image)]
path = getattr(node, "path")
print(path)
<details>
<summary>英文:</summary>
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)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论