Python类属性重复值问题:如何避免check变量保留旧值?
问题:check变量重复旧值的原因及修复方法
问题描述
输入hello&&后,check返回&&;输入bob(无非法字符)时,check仍返回&&,无法得到新输入对应的结果。尝试用check=check.replace(check,"")清空变量无效。
代码与输出
原代码
class Game: alphabet=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] def __init__(self): self.char_list='' def check_char(self,txt): for i in txt: if i not in self.alphabet: self.char_list+=i return self.char_list game=Game() limit=0 while not limit>4: text = list(input("Type your message:\n").lower()) print(text) check=game.check_char(text) print(check) limit+=1 continue if limit==5: break
原输出
Type your message: hello&& ['h', 'e', 'l', 'l', 'o', '&', '&'] && Type your message: bob ['b', 'o', 'b'] &&
原因分析
问题出在Game类的char_list属性上:
char_list是实例属性,在__init__中初始化一次后,每次调用check_char方法时,都会在原有值的基础上累加非法字符,不会自动清空。- 当输入
bob时,没有非法字符,char_list不会新增内容,所以返回的还是之前存储的&&。 - 你尝试修改的
check=check.replace(check,"")只是修改了局部变量check,并没有改变game实例中char_list的存储值,所以下次调用check_char时,还是会返回旧的char_list。
修复方案
有两种简单的修复方式:
方案1:每次调用check_char前清空char_list
修改check_char方法,在遍历输入文本前先清空self.char_list:
def check_char(self,txt): self.char_list = "" # 每次调用前清空旧值 for i in txt: if i not in self.alphabet: self.char_list += i return self.char_list
方案2:将char_list改为局部变量(更推荐)
不需要用实例属性存储临时结果,直接在方法内定义局部变量,每次调用方法时都会重新初始化:
def check_char(self,txt): char_list = "" # 局部变量,每次调用方法都会重新创建 for i in txt: if i not in self.alphabet: char_list += i return char_list
另外,原代码中的continue语句会跳过后面的if limit==5: break,不过这部分不影响当前问题的核心逻辑,可根据需要调整。
内容的提问来源于stack exchange,提问作者Trishna
相关产品推荐
相关产品推荐

