【问题标题】:How can I call an attribute of an object using something the user has entered?如何使用用户输入的内容调用对象的属性?
【发布时间】:2020-08-07 08:43:06
【问题描述】:

'''

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 正在寻找一个名为 'attribute_to_find' 的 'python_object' 属性,我已经想到了。

我希望用户能够输入一个属性并让程序打印出类实例中该属性的值,id 为“10021”(“id”是“python_object”的另一个属性)

有人知道我该怎么做吗?

谢谢:)

【问题讨论】:

    标签: python object python-object


    【解决方案1】:

    使用getattr(),将对象作为第一个参数传递,属性的字符串名称作为第二个参数如下:

    print(getattr(object_dict.get(i), attribute_to_find))
    

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多