0

class Journey has a list, self.leg_miles

class ManyJourneys has a list of journeys created by

self.journeys = []
for i in range(2):
    self.journeys.append(Journey())

from some input I add to the list leg_miles for each Journey kind of like this:

self.journeys[self.count].addLeg(temp)

temp is a number i read from a list. it is always changed to what was inputted right before the above line.

for some reason instead of creating a new list for journey[1] it just adds to the created list.

for example: if for journey[0] the leg_miles had [4,5,6] and I moved on to journey[1] to add 4 and 6 it would have : leg_miles = [4,5,6,4,6]

I do not understand why it is adding on. I have self in it. I do not understand how to upload code or pictures.

I hope this is enough information to solve the problem

EDIT: Here is the code I have.

class Journey:

    def __init__(self,odometer=0,leg_miles=[],leg_gas=[]):  #constructor
        self.odometer = odometer
        self.leg_miles = leg_miles
        self.leg_gas = leg_gas

    def addLeg(self,miles,gas):
        #adds to a list of miles and gas 
        self.leg_miles.append(miles)
        self.leg_gas.append(gas)

    def getLists(self):
        #returns the list of miles and the list of gas 
        return self.leg_miles,self.leg_gas

    def calculate(self):
        #calculate the miles per litre for the journey and return
        miles_per_litre = 0
        for i in range(len(self.leg_miles)):    #calcs miles per litre for each leg and adds to total
            miles_per_litre += int(self.leg_miles[i]/self.leg_gas[i])
        return miles_per_litre


class ManyJourneys:

    def __init__(self,name):

        self.myfile = open(name,"r")
        self.content = self.myfile.read().split("\n")

        self.journeys = []

        for i in range(self.content.count("")+1):
            self.journeys.append(Journey())

        self.count = 0

        for i in self.content:
            if i == "":
                self.count+=1
            else:
                temp = i.split(" ")
                self.journeys[self.count].addLeg(int(temp[0]),int(temp[1]))



    def statistics(self):

        sum = 0
        for i in self.journeys:
            sum += i.calculate()

        return sum/len(self.journeys)


def main():
    filename  = input("Please enter a file name. (Eg: test.txt): ")
    manyJourneys1 = ManyJourneys(filename)
    print("You got {0} miles per litre.".format(manyJourneys1.statistics()))

main()

and a sample text file would be

100 54
340 109
23 4

333 33
4500 678
RickeshM
  • 11
  • 1
  • 3
  • please show your `__init__` – m.wasowski Mar 25 '14 at 02:42
  • it's not enough, please include the unabridged code. – Brian Cain Mar 25 '14 at 02:43
  • What do you mean by "I do not understand how to upload code or pictures"? You can just put the code here. We need to see how did you implement the `addLeg` and how you did the `print` that will result in the problem you're describing – justhalf Mar 25 '14 at 02:43
  • are you doing `leg_miles = []` inside the class body? don't do that; assign it in the constructor, `__init__`. anything set in the class body is shared between all instances. – Eevee Mar 25 '14 at 02:49
  • possible duplicate of ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) – DSM Mar 25 '14 at 03:39

2 Answers2

2

There is an unobvious feature in Python regarding default values - they represent the same object each time, which causes surprising behavior when using mutable values as defaults:

def add(value, l=[]):
    l.append(value)
    return l

add(1) # [1]
add(2) # [1, 2]

To not fall into this trap do not use list or any other mutable value this way. If you need to initialize something to an empty list do it in a function/method body:

def __init__(self, odometer=0, leg_miles=None, leg_gas=None):
    self.odometer = odometer
    self.leg_miles = leg_miles or []
    self.leg_gas = leg_gas or []
Suor
  • 2,845
  • 1
  • 22
  • 28
0

You screwed up your definition of Journey. Mutable types must be assigned in the initializer or in methods, not in the class or default arguments.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358