如何在Python中使用`globals()`访问属性

huangapple go评论91阅读模式
英文:

how to access attributes using globals() in python

问题

  1. 我想访问一些树节点的属性之一,它们的名称类似于“image1image2,...”,所以我发现全局变量很酷,可以避免编写重复的代码;但是使用全局变量,我无法访问属性;我是 Python 新手,所以是的,我是新手。
  2. 这是我的代码:
  3. ```python
  4. Image1=Node("I1", path="path", parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
  5. print(globals()["Image"+str(image)+".path"])

出现了错误:

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

我尝试过:

  1. print(globals()[f"Image{str(image)}.path"])

并将全局变量的结果存储在另一个变量中,但这不是它的工作方式。

  1. <details>
  2. <summary>英文:</summary>
  3. I wanna access one of attributes of some of my tree nodes and their name is like &quot;image1,imag2,...&quot; so I found globals cool to avoid writing duplicated codes; but using globals i couldn&#39;t access attributes; i new to python so yup I&#39;m newbie.
  4. 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"])

  1. there is errors:

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

  1. i tried:
  2. print(globals()[f&quot;Image{str(image)}.path&quot;])
  3. and storing the globals outcome in an other variable but its not how it works.
  4. </details>
  5. # 答案1
  6. **得分**: 0
  7. 步骤1 ==&gt; 首先从全局变量中检索节点对象。
  8. 步骤2 ==&gt; 使用getattr()函数访问节点的属性。
  9. Image1 = Node("I1", path="路径", parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
  10. node = globals()["Image" + str(image)]
  11. path = getattr(node, "path")
  12. print(path)
  13. <details>
  14. <summary>英文:</summary>
  15. Step:1 ==&gt; First retrieve the node object from globals()
  16. Step:2 ==&gt; Use getattr() function to access the attribute of the node.
  17. Image1 = Node(&quot;I1&quot;, path=&quot;path&quot;, parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
  18. node = globals()[&quot;Image&quot; + str(image)]
  19. path = getattr(node, &quot;path&quot;)
  20. print(path)
  21. </details>

huangapple
  • 本文由 发表于 2023年3月12日 15:28:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定