variab中的全局dict名称

2024-03-29 08:53:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的房间里有更多的字典初始.py我想在变量中设置它的名称。但它不会把它当作名字。你知道吗

我的程序:

from StackOverflow import *

number = input("Wich car do you want:")
car = r"Car"+number
print(car["Color"])
print(car["Brand"])

StackOverflow\\初始化\uuuuuuuuuy.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

Tags: frompyimport程序名称number字典名字
3条回答

只有当变量在当前模块中时,使用全局变量的方法才有效。要在另一个模块中获取值,可以使用getattr:

import other
print getattr(other, "name_of_variable")

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

比如:

import StackOverflow
number = input("Wich car do you want:")
car = r"Car"+number
print (getattr(StackOverflow, car))

关于各种“eval”解决方案的注意事项:您应该小心使用eval,特别是当您要评估的字符串来自可能不受信任的源时,否则,如果您得到一个恶意字符串,您可能会最终删除磁盘的全部内容或类似的内容。你知道吗

尝试更改:

car = r"Car"+number

收件人:

car = globals()["Car" + number]

或:

car = eval("Car"+number)

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

相关问题 更多 >