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

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

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 &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.

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&quot;Image{str(image)}.path&quot;])
and storing the globals outcome in an other variable but its not how it works.

</details>


# 答案1
**得分**: 0


步骤1 ==&gt; 首先从全局变量中检索节点对象。

步骤2 ==&gt; 使用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 ==&gt; First retrieve the node object from globals()

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

   

    Image1 = Node(&quot;I1&quot;, path=&quot;path&quot;, parent=Images, priceL=prices[0:12], fp=np.array([70,172]))
    node = globals()[&quot;Image&quot; + str(image)] 
    path = getattr(node, &quot;path&quot;) 
    print(path)




</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:

确定