如何拆分字符串并传入对象__init__方法?解决Soda实例split报错
解决AttributeError: Soda instance has no attribute 'split'问题
咱们先直接说问题根源:你在getName()方法里调用了self.split(","),但这里的self是Soda类的实例对象,不是字符串!只有字符串类型才有split()方法,Python找不到Soda实例上的这个方法,自然就抛出了AttributeError。
接下来咱们按照你导师的要求来修正代码,保证逻辑符合作业要求:
第一步:修正Soda类的实现
你原本的思路是把整行包含所有信息的字符串传给Soda构造函数,然后在类内部拆分出名称、价格和数量——这个思路没问题,但错在拆分的对象用错了。我们需要把传入的字符串先存在实例里,再对这个字符串做拆分:
class Soda: # Constructor def __init__(self, data_str="", _price=0.0, _quantity=0): # 先把传入的整行数据字符串保存为实例属性 self._data_str = data_str # 通过自定义方法初始化各个核心属性 self._name = self.getName() self._price = self.getPrice() self._quantity = self.getQuantity() def getName(self): # 对保存的字符串进行拆分,提取名称 tempList = self._data_str.split(",") # 去除名称前后可能存在的多余空格 self._name = tempList[0].strip() return self._name def getPrice(self): # 拆分字符串并将价格转为浮点数 tempList = self._data_str.split(",") self._price = float(tempList[1].strip()) return self._price def getQuantity(self): # 拆分字符串并将数量转为整数 tempList = self._data_str.split(",") self._quantity = int(tempList[2].strip()) return self._quantity # 为后续计算添加单独的属性获取方法 def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity
第二步:微调fillMachine函数
你的原函数逻辑没问题,只是可以加个空行判断,避免读取到空行时创建无效对象:
from Sodas import Soda def fillMachine(filename) : # Create an empty list that will store pop machine data popMachine = [] # Open the file specified by filename for reading infile = open(filename, "r") # Loop to read each line from the file and append a new Soda object # based upon information from the line into the pop machine list. for line in infile : cleaned_line = line.strip() # 跳过空行 if cleaned_line: popMachine.append(Soda(cleaned_line)) # Close the file infile.close() # Return the pop machine list return popMachine
关键修正点说明
- 拆分对象正确了:现在我们是对
self._data_str(也就是传入的整行字符串)调用split(),而不是对Soda实例本身调用,解决了核心的AttributeError问题。 - 数据类型转换:把价格转为浮点数、数量转为整数,这样后续计算时不会出现类型错误。
- 处理多余空格:用
strip()去除每个字段前后的空格,避免因为文件里的空格导致数据错误(比如原文件里可能有的10 Coke之间的空格,更合理的文件格式应该是每行一个条目)。
这样修改后,popMachine就会正确包含3个Soda对象,每个对象都能通过get_name()、get_price()、get_quantity()方法单独获取对应属性,满足后续计算的需求。
内容的提问来源于stack exchange,提问作者Lauren Mabe
相关产品推荐
相关产品推荐

