Python OOP中类属性列表被识别为字符串的问题排查求助
问题原因及解决方案
核心错误原因
问题根源是App层输入的标签是字符串类型,但Note类的self.tags被设计为列表类型:
- 通过App的
add_note或modify_note方法输入标签时,input()返回的是字符串(比如输入"work,study"),直接传给Note类后,self.tags就变成了字符串,而字符串没有extend方法,调用add_tags时自然报错。 - 直接测试Note/Notebook类时你应该是传入了列表,所以没触发问题。
具体修复步骤
1. 修复App类的add_note方法
把输入的标签字符串分割为列表,同时处理标签前后的空格:
def add_note(self): memo = input("enter memo for note:") tags_input = input("Enter tags separated by commas:") # 将输入字符串转为标签列表,空输入则设为空列表 tags = [tag.strip() for tag in tags_input.split(',')] if tags_input else [] self.notebook.add_note(memo, tags) print("Note added ")
2. 修复App类的modify_note方法
同样处理修改时的标签输入,转为列表格式:
def modify_note(self): id = int(input('Input note Id to be modified or enter 0 to quit: ')) if id > 0: memo = input('Type in new memo or Press enter ') tags_input = input('Type in tags separated by comma or Press enter ') tags = [tag.strip() for tag in tags_input.split(',')] if tags_input else [] if memo or tags: self.notebook.modify_note(id, memo, tags)
3. 修复Note/Notebook类的可变默认参数陷阱(重要)
你的代码里用了tags=[]、notes=[]这种可变默认参数,这是Python常见陷阱——多次创建实例会共享同一个列表,导致标签/笔记互相污染。修改如下:
class Note: def __init__(self, memo, tags=None): global last_id last_id = last_id + 1 self.id = last_id self.created_on = datetime.date.today() self.memo = memo self.tags = tags if tags is not None else [] class Notebook: def __init__ (self, notes=None): self.notes = notes if notes is not None else []
验证效果
修改后,无论添加还是修改笔记,输入的逗号分隔标签都会被转为列表,self.tags始终保持列表类型,调用extend方法就不会再报错。
内容的提问来源于stack exchange,提问作者ArNY
相关产品推荐
相关产品推荐

