#Python 为什么我的这段代码一直收到 namedtuple 属性错误?

问题描述 投票:0回答:1

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

AttributeError: 'Contact' 对象没有属性'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)



python namedtuple
1个回答
1
投票

你可以使用 getattr(phonebook[find_name], find_info). 或者把你的Contact对象改成一个字典,这样你就可以直接使用find_info作为一个索引。如果你想同时访问属性和变量键,你可以研究一下 "AttrDict"。像访问属性一样访问dict键?


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
投票

你不能使用点符号来访问元组的属性。代码最终会寻找一个叫做'find_info'的方法,而这个方法并不存在。

你可以使用 .NET Framework 2.0 的方法来访问元组的属性。

getattr(phonebook[find_name], find_info)

来获取find_info变量所持有的属性。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.