Reputation: 516
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.
Upvotes: 2
Views: 843
Reputation: 33109
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.
Upvotes: 6