如何在 Python 中使用与对象同名的字符串来访问对象本身? [英] How can I use a string with the same name of an object in Python to access the object itself?

查看:56
本文介绍了如何在 Python 中使用与对象同名的字符串来访问对象本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在下面的代码中,我想使用 x 作为引用获取列表 [1,2,3].

输入[1]:pasta=[1,2,3]在:[2]:意大利面输出[2]:[1, 2, 3]在 [3] 中:x='pas'+'ta'在 [4] 中:x出[4]:'面食'

解决方案

你试图做的是一个不好的做法.

你真正需要的是一个dict:

<预><代码>>>>dct = {'面食':[1,2,3]}>>>x = 'pas' + 'ta'>>>dct[x][1, 2, 3]

这是您尝试实现的实际任务的正确数据结构:使用字符串访问对象.

其他答案建议(或只是穿着磨损的)不同的方法来做到这一点.由于 Python 是一种非常灵活的语言,您几乎总能找到不同的方法来完成给定的任务,但是应该有一种——最好只有一种——显而易见的方法"[1].

他们都会做这项工作,但并非没有缺点:

  • locals() 是可读性较差,不必要的复杂,并且在某些情况下也会面临风险(参见 Mark Byers 回答).如果您使用 locals(),您会将真实变量与数据库变量混合在一起,这很混乱.
  • eval() 是简单丑陋,是一种动态获取一些源代码的快速而肮脏的方式"[2]不良做法.

如果对正确的选择方式有疑问,请尝试遵循 Python 之禅 可能是一个开始.

嘿,即使是 InteractiveInterpreter 可用于使用字符串访问对象,但这并不意味着我要这样做.

For example, in the code below I would like to obtain the list [1,2,3] using x as a reference.

In[1]: pasta=[1,2,3]
In:[2]: pasta
Out[2]: [1, 2, 3]
In [3]: x='pas'+'ta'
In [4]: x
Out[4]: 'pasta'

解决方案

What you are trying to do is a bad practice.

What you really need is a dict:

>>> dct = {'pasta': [1,2,3]}
>>> x = 'pas' + 'ta'
>>> dct[x]
[1, 2, 3]

This is the right data structure for the actual task you're trying to achieve: using a string to access an object.

Other answers suggested (or just showed with a worning) different ways to do that. Since Python is a very flexible language, you can almost always found such different ways to follow for a given task, but "there should be one-- and preferably only one --obvious way to do it"[1].

All of them will do the work, but not without downsides:

  • locals() is less readable, needlessly complex and also open to risks in some cases (see Mark Byers answer). If you use locals() you are going to mix the real variables with the database ones, it's messy.
  • eval() is plain ugly, is a "quick-and-dirty way to get some source code dynamically"[2] and a bad practice.

When in doubt about the right way to choose, tring to follow the Zen of Python might be a start.

And hey, even the InteractiveInterpreter could be used to access an object using a string, but that doesn't mean I'm going to.

这篇关于如何在 Python 中使用与对象同名的字符串来访问对象本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆