views:

46

answers:

1

I am trying to define a variable in a class that then can be accessed/changed from functions within that class.

For example:

class MyFunctions():
    def __init__( self):
        self.listOfItems = []

    def displayList( self):
        """Prints all items in listOfItems)"""
        for item in self.listOfItems:
            print item

    def addToList(self):
        """Updates all mlb scores, and places results in a variable."""
        self.listOfItems.append("test")

f = MyFunctions()
f.addToList
f.displayList

This should output all of the items in the list for me, but instead it displays nothing. I am assuming this is occuring because I did not setup the scope of the variables correctly. I want to be able to access and change listOfItems from within all of the functions in MyFuctions.

I have been trying to figure this out for a few hours now, so any help would be greatly appreciated.

+6  A: 

f.addToList and f.displayList do not invoke the methods addToList and displayList respectively. They simply evaluate to the method (bound to the object f in this case) themselves. Add parentheses to invoke the methods as in the corrected version of the program:

class MyFunctions():
    def __init__( self):
        self.listOfItems = []

    def displayList( self):
        """Prints all items in listOfItems)"""
        for item in self.listOfItems:
            print item

    def addToList(self):
        """Updates all mlb scores, and places results in a variable."""
        self.listOfItems.append("test")

f = MyFunctions()
f.addToList()
f.displayList()

This is in contrast to Ruby which does not require parentheses for method invocation (except to eliminate ambiguity in certain cases).

It is instructive to add the following to the end of your program:

print type(f.addToList)

This will output something like the following:

<type 'instancemethod'>

demonstrating that this is a method reference and not a method invocation.

Richard Cook
Thank you for the help! I was looking for the wrong thing. You saved me a ton of time!
xur17
FWIW, this is where Python's interactive mode proves its worth. You can run a script and have it drop you to interactive shell by running `python -i myscript.py`. From there you can tinker with the script's environment interactively. For example had you called `f.addToList` interactively, you would have seen that it is a bound method. :)
jathanism
@xur17: You should mark this as the accepted answer by clicking the check box to the left.
Daenyth