“”“
class python_object:
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
#object_dict is made by importing JSON objects and looks like this
object_dict = {1: <__main__.python_object object at 0x00000283EBD7CEC8>,
2: <__main__.python_object object at 0x00000283EBD7CF08>,
3: <__main__.python_object object at 0x00000283EBD7CF48>,
4: <__main__.python_object object at 0x00000283EBD7CF88>}
#///some other code///
id = "10021"
attribute_to_find = input("Enter an Attribute: ")
for i in range(1, len(object_dict)+1):
if (object_dict.get(i)).id == id_to_find:
print(object_dict.get(i).attribute_to_find)“”“
这是不起作用的,因为Python正在寻找一个名为“python_object_to_find”的属性,这是我想过的。
我希望用户能够输入一个属性,并让程序在id为"10021“的类实例中打印出该属性值('id‘是’python_object‘的另一个属性)
有人知道我会怎么做吗?
谢谢:)
发布于 2020-04-24 05:22:03
使用getattr(),将对象作为第一个参数传递,将属性的字符串名称作为第二个参数传递,如下所示:
print(getattr(object_dict.get(i), attribute_to_find))https://stackoverflow.com/questions/61397133
复制相似问题