【发布时间】:2018-05-14 02:38:53
【问题描述】:
我正在尝试使用文件中的信息创建 Soda 对象的多个实例。该文件的格式如下名称,价格,编号
Mtn. Dew,1.00,10
Coke,1.50,8
Sprite,2.00,3
我的代码是这样的(这是 main() 中的一个函数):
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 :
popMachine.append(Soda(str(line.strip())))
# Close the file
infile.close()
# Return the pop machine list
return popMachine
如果我猜对了,popMachine 应该是 3 个不同的 Soda 对象的列表,每个对象都有一行输入文件。
然后,在我的班级中,我需要能够获得名称、价格或数量,以便以后用于计算。我的苏打水课代码如下所示:
#Constructor
def __init__(self, _name = "", _price = 0.0, _quantity = 0) :
self._name = self.getName()
self._price = _price
self._quantity = _quantity
def getName(self) :
tempList = self.split(",")
self._name = tempList[0]
return self._name
这是我遇到问题的地方。 IIRC self 代替主代码中的行,因此 self 应该是一个字符串,例如“Mtn.Dew,1.00,10”,并且 split(",") 方法的预期结果应该形成一个类似 ["Mtn . Dew", "1.00", "10"] 然后我可以使用该列表的索引来返回名称。
但是,我收到此错误“AttributeError: Soda instance has no attribute 'split'”而且我不知道为什么。此外,这段代码中的所有 cmets 都来自我的导师,作为作业的一部分,所以即使有更快/更好的方法来完成这一切,这也是我必须这样做的方式:/
【问题讨论】:
-
self指的是您的 Soda 实例,因此除非您定义一个名为split的方法,否则它没有。 -
您实际上没有将字符串传递给
getName或__init__。 Calingself.getName()没有传入任何字符串。 -
在这种情况下,
__init__需要正确的参数(name,price,number),而不是字符串。所以 Pythonic 的事情是添加一个 staticmethodfrom_string/make/make_from_string,然后 调用Soda()构造函数。而不是您的getName被从构造函数调用,这是一个更加痛苦的分解。
标签: python class split factory static-methods