Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this simple python class not working?

Tags:

python

list

class

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.

like image 880
Michael Avatar asked Mar 12 '26 12:03

Michael


2 Answers

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]]     
like image 182
Tom Leys Avatar answered Mar 15 '26 01:03

Tom Leys


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

like image 35
Harriv Avatar answered Mar 15 '26 03:03

Harriv