I am trying to create multiple instances of a Soda object using information from a file. The file is formatted like this Name,price,number
Mtn. Dew,1.00,10
Coke,1.50,8
Sprite,2.00,3
My code I have is this (this is a function within 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
If I got this right, popMachine should be a list of 3 different Soda objects, each with one line of the input file.
Within my class, I then need to be able to get just the name or price or quantity for use in calculations later. My class Sodas code looks like this:
#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
This is where I run into problems. IIRC self stands in place of line in the main code, so self should be a string such as "Mtn. Dew,1.00,10" and the expected outcome of the split(",") method should form a list like ["Mtn. Dew", "1.00", "10"] where I can then use the index of that list to return just the name.
However, I get this error "AttributeError: Soda instance has no attribute 'split'" And I'm not sure why. Also, all the comments in this code came from my instructor as part of the assignment, so even if there are quicker/better methods for doing this whole thing, this is the way I have to do it :/