如何使用用户输入的内容调用对象的属性?
How can I call an attribute of an object using something the user has entered?
'''
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' 的一个名为 'attribute_to_find' 的属性,我已经猜到这么多了。
我希望用户能够输入一个属性并让程序在 ID 为“10021”的 class 实例中打印出该属性的值('id' 是另一个属性'python_object')
有人知道我该怎么做吗?
谢谢:)
使用getattr()
,传递对象作为第一个参数,属性的字符串名称作为第二个参数如下:
print(getattr(object_dict.get(i), attribute_to_find))
'''
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' 的一个名为 'attribute_to_find' 的属性,我已经猜到这么多了。
我希望用户能够输入一个属性并让程序在 ID 为“10021”的 class 实例中打印出该属性的值('id' 是另一个属性'python_object')
有人知道我该怎么做吗?
谢谢:)
使用getattr()
,传递对象作为第一个参数,属性的字符串名称作为第二个参数如下:
print(getattr(object_dict.get(i), attribute_to_find))