You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

联系人列表校验异常:仅识别初始对象,无法检测追加对象

联系人列表号码重复校验问题修复

核心问题是数据类型不匹配:创建Contact对象时,把用户输入的号码以字符串形式存入number属性,但校验重复时,却将新输入的号码转成整数去和已存的字符串号码比较——字符串与整数永远不会相等,导致后续追加的联系人无法被检测到号码重复。

修复方案

统一号码的存储与校验逻辑,保持类型一致(推荐用字符串存储,避免丢失号码前导零或特殊格式):

  • 校验重复时,直接用输入的字符串号码和已存联系人的number字符串比较,无需转成整数
  • 保持Contact类中number属性的字符串存储逻辑不变

修复后的完整代码

class Contact:
    def __init__(self, name, number, address):
        self.name = name
        self.number = number
        self.address = address

    def __str__(self):
        return f"{self.name}, ({self.number}), {self.address}"


contact_list = []


def add_contact():
    global contact_list
    valid_name = False
    valid_number = False
    while not valid_name:
        contact_name = input("Who would you like to add as your contact?: ")
        name_taken = False
        for contact in contact_list:
            if contact.name == contact_name:
                print("Name is taken in contacts!")
                name_taken = True
                break
        if not name_taken:
            valid_name = True
    while not valid_number:
        contact_number = input("What is their number?: ")
        if len(contact_number) == 10 and contact_number.isnumeric():
            number_taken = False
            # 修复:直接用字符串比较,不再转int
            for contact in contact_list:
                if contact.number == contact_number:
                    print("Number is taken in contacts!")
                    number_taken = True
                    break
            if not number_taken:
                valid_number = True
            else:
                valid_number = False
        else:
            print("Invalid number!")
    contact_address = input("What is their house address?: ")
    new_contact = Contact(contact_name, contact_number, contact_address)
    contact_list.append(new_contact)
    print("Contact list:")
    for contact in contact_list:
        print("- " + str(contact))  # 标准写法:用str()触发__str__方法


add_contact()
add_contact()

内容的提问来源于stack exchange,提问作者bon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:45:32