繁体   English   中英

#Python 为什么我不断收到此代码的命名元组属性错误?

[英]#Python Why do I keep getting namedtuple attribute error for this code?

当我运行如下代码时,它返回属性错误。

AttributeError:“联系人”object 没有属性“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)



您的问题是您将find_info视为consult_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(getattr(phonebook[find_name], find_info))

使用getattr(phonebook[find_name], find_info)时,您实际上是在从您的联系人获取存储在 find_info 中的属性。

您可以使用getattr(phonebook[find_name], find_info) 或者也许将您的 Contact object 更改为字典,以便您可以直接使用 find_info 作为索引。 如果您想要属性和变量键访问,您可以查看某种“AttrDict”: 像属性一样访问字典键?

您不能使用点符号来访问元组的属性。 代码最终会寻找一个名为“find_info”的方法,但该方法并不存在。

您可以使用:

getattr(phonebook[find_name], find_info)

获取 find_info 变量持有的属性。

在您的代码中,find_info 的值类型是字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM