I can’t figure out what I’m doing wrong. I have to create a nested list(of possible solutions to a problem), so I created a class that appends a solution to a list of existing solutions(since each solution is being calculated one at a time)
This function works fine:
def appendList(list):
#print list
list2.append(list)
x =0
while x < 10:
x = x+1
one = "one"
two = "two"
appendList([(one), (two)])
print list2
with a result of:
[['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two'], ['one', 'two']]
but when I take this exact same function and put it in a class, I get an error saying:
TypeError: appendList() takes exactly 1 argument (2 given)
Here’s the class and how I call it:
class SolutionsAppendList: list2 = [] def appendList(list): #print list list2.append(list)
appendList.appendList([('one'), ('two')])
I’m sure I’m making a very basic error but I can’t seem to figure out why, since I’m using the same function in the class.
Any suggestions/advice would be great.
Thanks
Since you’re dealing with classes here, it’s important to use
instance variables. These can be accessed by using theselfkeyword. And if you’re dealing with class methods, be sure to make their first argumentself. So, modified…What’s cool about this is that you no longer need
list2. Instance variables (self.list). Are different than local variables (thelistyou pass to theappendList()method). EDIT: I”ve also added an__init__method, which is called once an instance of theSolutionsAppendListobject is created. In my first reply, I overlooked the fact thatself.*is not available outside of a method. This is the edited code (Thanks David).