0

Here's the code I'm trying to use. Works just fine if I use getset_pos as a function instead of a method here. edit: correction to line 6 (getset_pos is now self.getset_pos); edit2: added call to class at end

class Main:
    def __init__(self):
        self.i = [5, 5]
        self.o = []

        self.getset_pos(self.i, self.o)

    def getset_pos(self, input, output):
        """ Takes the coord of an item and sets it equal to another item """
        output = []
        for numb in input:
            output.append(numb)
        print output

test = Main()
test

I could have the getset_pos() method work specifically for self.i and self.o variables, however, I found this was more of what I wanted:

class Main:
    def __init__(self):
        self.i = [5, 5]
        self.o = []

        def getset_pos(input, output):
            output = []
            for numb in input:
                output.append(numb)
            return output

        getset_pos(self.i, self.o)

test = Main()
test

This function will just allow me to update the value of a variable to another variable more easily whenever I call this function. I only need to call it within the method.

James T.
  • 910
  • 1
  • 11
  • 24
  • One suggestion as a new SO user is to describe the error you are receiving. For example, does it give the wrong output, if so, what is the output, or perhaps it crashes or throws and exception etc... I suspect your code is giving you a name not found exception? – Peter M Jul 18 '14 at 23:53

2 Answers2

3

You cannot perform assignments to a reference that is passed in as an argument, and expect that assignment to be reflected outside the method. The answers to this question go into the details of why.

A more direct approach would be to simply use the self reference and skip passing the extra parameter.

class Main:
    def __init__(self):
        self.i = [5, 5]
        self.o = []

        self.getset_pos()

    def getset_pos(self):
        """ Takes the coord of an item and sets it equal to another item """
        self.o = []
        for numb in input:
            self.o.append(numb)
        print output
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

Python doesn't deal with blatant pointers, so it can be a bit awkward figuring out exactly what happens when you mess with it. Take a look at this for a good overview.

WHen you call getset_pos, output is a list which is mutable. Therefore when you use the append method, you are modifying the variable you pass in. However, since you explicitly set output=[] inside the function, you are no longer accessing the variable that was originally passed in - you have created a new list.

Community
  • 1
  • 1
AMacK
  • 1,396
  • 9
  • 9