tags:

views:

125

answers:

2

Hi,

I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here'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'm not very clear, I'm a bit new to oop, can you please help me cos I don't know what I'm doing wrong. Thanks.

+7  A: 

In Python, when you are writing methods inside an object, you need to prefix all references to variables belonging to that object with self. - like so:

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 before was creating and modifying a local variable called lst, so it would appear to "disappear" between calls.

Also, it is usual to make a constructor, which has the 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 so

>>> newlist=getlist(1,2,3, [4,5])
>>> newlist.printlist()
[1, 2, 3, [4,5]]
Tom Leys
Thats great, thanks very much!
Michael
@Michael - My pleasure :)
Tom Leys
+3  A: 

You should use "self.lst" instead of "lst". Without the "self", it's just internal variable to current method.

Harriv
Thats brilliant, that seems to have sorted it, Thanks for the help everyone!
Michael