Python中类对象列表无法保留已追加元素问题求助
问题分析与修复
你的代码存在几个关键问题,导致spam_inbox无法正确累积垃圾邮件:
1. 未创建Email对象列表
当前mailbox是字符串列表,没有实例化Email类对象,且代码中使用的inbox变量未定义,运行时会直接报错。需要先把邮箱内容转换成Email实例:
# 替换原来的mailbox定义,创建Email对象列表 inbox = [ Email("testing class variable in python", "example@gmail.com"), Email("testing variable in python", "exampleagain@yahoo.com") ]
2. mark_as_spam方法无返回值
mark_as_spam方法仅修改is_spam属性,默认返回None。你把这个返回值追加到spam_inbox,导致列表里都是None而非邮件对象。应该在标记后直接添加对应的邮件对象:
def get_spam_emails(): user_choose = int(input("\nWhich email would you like to mark spam? Enter index number(eg: 0 for the first email): ")) # 获取邮件对象并标记为垃圾邮件 email = inbox[user_choose] email.mark_as_spam() # 追加邮件对象而非方法返回值 spam_inbox.append(email) print(f"已标记为垃圾邮件:{email}") print("=======") return spam_inbox
3. 变量作用域声明(可选但稳妥)
虽然spam_inbox定义在函数外部,若后续需要修改它的赋值操作,建议显式声明global避免作用域问题:
def get_spam_emails(): global spam_inbox # 声明使用全局变量 user_choose = int(input("\nWhich email would you like to mark spam? Enter index number(eg: 0 for the first email): ")) email = inbox[user_choose] email.mark_as_spam() spam_inbox.append(email) print(f"已标记为垃圾邮件:{email}") print("=======") return spam_inbox
完整修复后的代码
class Email(): has_been_read = False is_spam = False def __init__(self, email_contents, from_address): self.email_contents = email_contents self.from_address = from_address def __str__(self): return f"{self.email_contents} from {self.from_address}" def mark_as_read(self): self.has_been_read = True def mark_as_spam(self): self.is_spam = True # 创建Email对象列表,替换原mailbox inbox = [ Email("testing class variable in python", "example@gmail.com"), Email("testing variable in python", "exampleagain@yahoo.com") ] user_choice = "" spam_inbox = [] def get_spam_emails(): global spam_inbox user_choose = int(input("\nWhich email would you like to mark spam? Enter index number(eg: 0 for the first email): ")) email = inbox[user_choose] email.mark_as_spam() spam_inbox.append(email) print(f"已标记为垃圾邮件:{email}") print("=======") return spam_inbox # while循环处理用户选择 while user_choice != "quit": user_choice = input("What would you like to do - read/mark spam/send/quit? ") if user_choice == "mark spam": get_spam_emails()
现在运行代码,标记多个邮件后,spam_inbox会正确累积所有被标记的Email对象。如果需要输出你期望的字符串格式,可通过列表推导转换:
print([str(email) for email in spam_inbox])
内容的提问来源于stack exchange,提问作者eli_257
相关产品推荐
相关产品推荐

