首页 > 解决方案 > 变量中的全局字典名称

问题描述

我想在我的 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

标签: pythonpython-3.x

解决方案


从 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')

推荐阅读