Why isn't this simple python class working?
I am trying to create a class that will receive a list of numbers and then print them out when I need to. I need to render 2 objects from a class in order to get two different lists. That's what I have so far
class getlist:
def newlist(self,*number):
lst=[]
self.number=number
lst.append(number)
def printlist(self):
return lst
Sorry I don't really understand, I'm a bit new to oop, could you please help me out because I don't know what I am doing wrong. Thank.
source to share
In Python, when you write methods inside an object, you need to attach all references to variables belonging to that object with self. - like this:
class getlist:
def newlist(self,*number):
self.lst=[]
self.lst += number #I changed this to add all args to the list
def printlist(self):
return self.lst
The code you had earlier was creating and modifying the local lst variable, so it seemed to "disappear" between calls.
In addition, a constructor is usually created that has a special name __init__
:
class getlist:
#Init constructor
def __init__(self,*number):
self.lst=[]
self.lst += number #I changed this to add all args to the list
def printlist(self):
return self.lst
Finally, use like this
>>> newlist=getlist(1,2,3, [4,5])
>>> newlist.printlist()
[1, 2, 3, [4,5]]
source to share