为什么这个简单的python类不起作用?

Mic*_*ael 3 python class list

我正在尝试创建一个可以获取数字列表的类,然后在需要时将其打印出来.我需要能够从类中生成2个对象以获得两个不同的列表.这是我到目前为止所拥有的

class getlist:   
    def newlist(self,*number):
        lst=[]
        self.number=number
        lst.append(number)

    def printlist(self):
        return lst
Run Code Online (Sandbox Code Playgroud)

对不起,我不是很清楚,我对oop有点新意,请你帮助我,因为我不知道我做错了什么.谢谢.

Tom*_*eys 7

在Python中,当您在对象内部编写方法时,您需要使用self为所有对该对象的变量的引用添加前缀. - 像这样:

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
Run Code Online (Sandbox Code Playgroud)

您之前使用的代码是创建和修改名为lst的局部变量,因此它似乎在调用之间"消失".

此外,通常创建一个具有特殊名称的构造函数__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
Run Code Online (Sandbox Code Playgroud)

最后,像这样使用

>>> newlist=getlist(1,2,3, [4,5])
>>> newlist.printlist()
[1, 2, 3, [4,5]]     
Run Code Online (Sandbox Code Playgroud)