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

Python列表遍历方法咨询:工单系统无法正常打印工单信息

解决工单系统打印所有工单的问题

核心问题

遍历Object_List打印Ticket对象时,Python默认输出对象的内存地址而非工单信息——因为Ticket类未定义将对象转换为可读字符串的方法。另外还有工单编号固定为2000的问题,每个工单应该拥有唯一递增的编号。

修改步骤

1. 给Ticket类添加__str__方法并修复编号逻辑

修改ticket.py,添加__str__方法让打印对象时输出格式化信息,同时用类变量实现工单编号递增:

#ticket.py
class Ticket():
    # 类变量记录下一个工单编号,初始为2000
    next_ticket_num = 2000
    
    def __init__(self, staffid, staffname, staffemail, issue):
        # 为当前工单分配编号,然后递增类变量
        self.ticketnum = Ticket.next_ticket_num
        Ticket.next_ticket_num += 1
        
        self.staffid = staffid
        self.staffname = staffname
        self.staffemail = staffemail
        self.issue = issue
        self.status = 'open'
        self.answer = 'None'

    # 定义__str__方法,返回可读的工单信息
    def __str__(self):
        return (f"工单编号: {self.ticketnum}\n"
                f"员工ID: {self.staffid}\n"
                f"员工姓名: {self.staffname}\n"
                f"员工邮箱: {self.staffemail}\n"
                f"问题描述: {self.issue}\n"
                f"工单状态: {self.status}\n"
                f"回复内容: {self.answer}\n"
                "------------------------")

2. 修正main.py中的工单展示函数

原stats函数命名不符合功能定位,重命名为show_all_tickets,同时优化空列表提示:

#main.py
# 替换原stats函数
def show_all_tickets():
    if not Object_List:
        print("暂无任何工单")
        return
    print("所有工单信息:")
    for ticket in Object_List:
        print(ticket)

然后在selection函数中,将op == 2的调用改为新函数:

elif op == 2:
    show_all_tickets()

3. 可选优化(提升代码健壮性)

  • 给MenuList的menu方法添加静态方法装饰器,符合类方法规范:
class MenuList(object):
    @staticmethod
    def menu():
        # 原菜单代码不变
  • 将submit函数的递归调用改为循环,避免递归深度问题:
def submit():
    while True:
        staffname = input('Enter staff name: ')
        staffid = input('Enter staff ID: ')
        staffemail = input('Enter email address: ')
        issue = input('Description of issue: ')
        if issue == 'Password change':
            newpass = staffid[0:2] + staffname[0:3]
            print("Your new password is: " + newpass)
        ticketobject = Ticket(staffid, staffname, staffemail, issue)
        Object_List.append(ticketobject)

        Newticket = input('Do you have another problem to submit? (Y/N)')
        if Newticket != 'Y':
            break
    return selection()

修改说明

  • __str__是Python特殊方法,调用print()打印对象时会自动执行该方法,返回的字符串就是最终显示的内容。
  • 用类变量next_ticket_num统一管理编号,确保每个工单编号唯一且递增。
  • 函数重命名后更符合“见名知意”的代码规范,降低维护成本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:50:35