当我运行以下代码时,它将返回属性错误。
AttributeError:“联系人”对象没有属性“ find_info”
我该如何解决?
phonebook = {}
Contact = namedtuple('Contact', ['phone', 'email', 'address'])
def add_contact(phonebook):
name = input()
phone = input()
email = input()
address = input()
phonebook[name] = Contact(phone, email, address)
print('Contact {} with phone {}, email {}, and address {} has been added successfully!' .format(name, phonebook[name].phone, phonebook[name].email, phonebook[name].address))
num = 0
for i in phonebook.keys():
if i in phonebook.keys():
num += 1
print('You now have', num, 'contact(s) in your phonebook.')
def consult_contact(phonebook):
find_name = input('What is the name of the contact?\n')
find_info = input('What information do you need?\n')
if find_name not in phonebook:
print('Contact not found!')
else:
print(phonebook[find_name].find_info)
if __name__ == "__main__":
add_contact(phonebook)
consult_contact(phonebook)
答案 0 :(得分:2)
您的问题是您正在将find_info
视为咨询电话簿中的属性。
尝试一下:
def consult_contact(phonebook):
find_name = input('What is the name of the contact?\n')
find_info = input('What information do you need?\n')
if find_name not in phonebook:
print('Contact not found!')
else:
print(getattr(phonebook[find_name], find_info))
使用getattr(phonebook[find_name], find_info)
时,实际上是从联系人中获取存储在find_info中的属性。
答案 1 :(得分:1)
您可以使用getattr(phonebook[find_name], find_info)
。或将Contact对象更改为字典,以便可以直接使用find_info作为索引。如果您想同时访问属性和变量键,可以查看某种“ AttrDict”:Accessing dict keys like an attribute?
答案 2 :(得分:1)
您不能使用点表示法来访问元组的属性。该代码最终将查找不存在的名为“ find_info”的方法。
您可以使用:
const query1 = 'SELECT NOW() as now'
const query2 = 'SELECT * from table1'
return new Promise((resolve, reject) => {
pgClient
.query(query1)
.then(res => {
pgClient
.query(query2)
.then(res => {
resolve(res.rows[0])
})
.catch(e => reject(e.stack))
})
.catch(e => reject(e.stack))
});
要获取find_info变量拥有的属性。
答案 3 :(得分:0)
在您的代码中,find_info的值类型为字符串。