如何比较 Python 中对象属性的值?
How can I compare the value of an object's attribute in Python?
因此,我正在使用 mongoDB 和我的查询 return 对象数组。对象看起来像这样:
{
'_id': ObjectId('5ff891bc20cb7d29dc1d836c'),
'Model': 'X1150',
'Platform': 'Server',
'# of CPU Cores': 4,
'# of Threads': 4
}
假设我将此特定文档存储在变量 doc
中
现在,我希望能够将 'Platform' 属性与字符串进行比较。例如,在 JavaScript 中,我会这样做:
if (doc.Platform == 'Server') return 1;
但它似乎在 python 中不起作用(可能是因为该属性是一个字符串?)。我怎样才能正确地进行这种比较?
谢谢!
你说返回的对象好像是字典,你可以type(doc)
查一下。如果是这样,那么 if (doc['Platform'] == 'Server') return 1;
应该可以工作
因此,我正在使用 mongoDB 和我的查询 return 对象数组。对象看起来像这样:
{
'_id': ObjectId('5ff891bc20cb7d29dc1d836c'),
'Model': 'X1150',
'Platform': 'Server',
'# of CPU Cores': 4,
'# of Threads': 4
}
假设我将此特定文档存储在变量 doc
现在,我希望能够将 'Platform' 属性与字符串进行比较。例如,在 JavaScript 中,我会这样做:
if (doc.Platform == 'Server') return 1;
但它似乎在 python 中不起作用(可能是因为该属性是一个字符串?)。我怎样才能正确地进行这种比较?
谢谢!
你说返回的对象好像是字典,你可以type(doc)
查一下。如果是这样,那么 if (doc['Platform'] == 'Server') return 1;
应该可以工作