python - 变量中的全局字典名称
问题描述
我想在我的 init.py 中有更多的字典,我想在一个变量中设置它的名字。但它不会将其检测为名称。
我的程序:
from StackOverflow import *
number = input("Wich car do you want:")
car = r"Car"+number
print(car["Color"])
print(car["Brand"])
StackOverflow\__init__.py:
Car1 = {
"Color": "Blue",
"Brand": "Aston Martin"
}
Car2 = {
"Color": "Red",
"Brand": "Volvo"
}
我希望它能提供所选汽车的颜色和品牌。但我得到这个错误:
Traceback (most recent call last):
File "D:/Users/stanw/Documents/Projecten/Stani Bot/Programma's/StackOverflow/Choose Car.py", line 5, in <module>
print(car["Color"])
TypeError: string indices must be integers
解决方案
从 Python 3.7 开始,您可以getattr
在模块上使用。
import StackOverflow
number = input('Enter a number')
var_name = f'Car{number}'
if hasattr(StackOverflow, var_name):
car = getattr(StackOverflow, var_name)
else:
print('Car not found')
推荐阅读
- geojson - GDALException OGR 失败
- c# - 是否可以在 EF Core Include 查询中加入不相关的表
- python - pandas 风格高亮格式的分步说明是什么?
- xcode - 我可以用一些模板自动填充 Xcode 的提交消息吗?
- java - 为什么将微服务分布式事务的模式命名为 SAGA?
- vba - 在字符之间插入换行符
- java - 如何在保留 Java 中的所有空格的同时将字符串拆分为句子?
- javascript - 在 Azure Web 应用服务中托管静态 HTML
- rust - 如何使用 proc 宏来创建可能违反卫生的宏?
- javascript - Jquery选项卡在淡入淡出动画之前发生变化