python - 如何制作对象的列表元素实例
问题描述
我正在尝试遍历字符串列表并使每个元素成为对象的实例。我制作了一个简化版本只是为了演示我的问题。当我运行此代码时,我收到一条错误消息,指出未定义“David”。我明白我做错了什么:当我写 'People[i] = Person()' 时,People[i] 变成了变量名,而不是调用列表中的每个元素。
如何调用列表中的每个元素并使其成为变量,以便在这种情况下,当我打印(David.name)时,它会打印“大卫”?
class Person:
def __init__(self):
self.name = "Unassigned"
People = ["David", "Emma", "Brian"]
for i in range(len(People)):
People[i] = Person()
print(David.name)
解决方案
不要分配这样的变量名或弄乱全局变量。改用字典:
class Person:
def __init__(self):
self.name = 'Unassigned'
People = ["David", "Emma", "Brian"]
#create a list of your objects
obj_list = [Person() for i in range(len(People))]
#convert People names to dictionary keys
dictionary = dict(zip(People, obj_list))
print(dictionary['David'].name)
#Unassigned
推荐阅读
- flutter - Flutter showModalBottomSheet 隐藏在 CupertinoTabBar 后面
- ios - iOS 14:如何在 Safari 应用程序中打开 URL,而不是用户配置的默认浏览器?
- .htaccess - 使用 php 上传文件并在 msql 和 htaccess 的帮助下显示为网页
- git - 如何更改 GitHub 中的提交历史记录?
- amazon-web-services - Terraform - 错误:找不到匹配的 Route53Zone
- mongodb - mongoDB Atlas 的目标 IP 是什么?
- python - python的内置排序是否并行化?
- c++ - C++ 向量和 cin
- redis - 我们可以使用 Redis 集群可靠地扩展 URL 更短的服务吗?(即我们需要 Zookeeper 吗?)
- python - TesseractNotFoundError: ** tesseract 可执行文件的路径** ArchLinux(ManjoraLinux)