从用户输入创建动态命名的变量 [英] Creating dynamically named variables from user input

查看:36
本文介绍了从用户输入创建动态命名的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学习编程,并且正在学习 Python 作为我的第一语言.作为练习,我正在尝试编写一个地址簿程序.新联系人由用户使用命令提示符创建.新联系人是 Contacts 类的对象实例.

I'm just learning to program and am learning Python as my first language. As an exercise I'm trying to write an address book program. New contact are created by the user using the command prompt. New contacts are object instances of the Contacts class.

我知道如何从代码中实例化一个类对象,但如何根据用户输入创建一个具有变量名的对象?假设我提示用户输入名称——我如何获取该信息并将其用于我的新对象的变量名称?

I know how to instantiate a class object from within the code, but how do I create one with a variable name based on user input? Say I prompt the user for a name -- how do I take that info and use it for the variable name of my new object?

谢谢!!

推荐答案

从评论中可以看出,您所问的问题在这里不止一次被问到.如何创建动态命名的变量".

From the comments, it turns out you are asking about something that gets asked more than once on here. "How can I create dynamically named variables".

答案:不要这样做.可能有更好的方法来解决问题.

Answer: Don't do this. Chances are there are better ways to solve the problem.

说明:

如果您要创建动态命名的变量,一旦创建它们,您就无法很好地处理它们.当然有办法检查全局和局部范围以查看那里有什么.但事实是,您应该对正在创建的内容拥有明确的控制权.

If you were to create dynamically named variables, you don't quite have a good handle to them once they are created. Sure there are ways to check the globals and local scopes to see what is there. But the fact is that you should have definitive control over what is being created.

你应该做的是把它们放进字典里:

What you should do is put them into a dictionary:

people = {}
name = raw_input("What name? ") # "person"
people[name] = User(name)

print people
# {'person': <User: "person">}

print people.keys()
# ['person']

这样您就不会在命名空间中创建任意变量.您现在有一个键和对象作为值的字典.它也是一种允许用户提供的输入来驱动变量命名的蠕虫.

This way you are not creating arbitrary variables in your namespace. You now have a dictionary of keys and objects as values. It is also a can of worms to allow a user-supplied input to drive the naming of a variable.

有关更多信息,只需在此处搜索同一主题并查看大量示例,说明您不应这样做的原因.无论您看到什么示例向您展示如何使用 globals() 等,请采纳我的建议,不要走那条路.爱和享受......也许拥抱和亲吻,你的字典.

For more info, just search on here for the same topic and see numerous examples of why you should not do this. No matter what examples you see showing you how to use globals(), etc, please take my advise and don't go that route. Love and enjoy..and maybe hug and kiss, your dictionary.

参考文献:

  • How can you dynamically create variables via a while loop?
  • Is it possible to "dynamically" create local variables in Python? (DONT DO THIS)

这篇关于从用户输入创建动态命名的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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