Python类函数,无法追加到列表

时间:2019-11-19 00:55:27

标签: python python-3.x

class A:
def __init__(self):
    self._list = []

def addItem(self, x):
    self._list.append(x)



def main():
    while True:
        option = int(input("Enter option: "))
        if option == 1:
            A().addItem("hello")
        if option == 2:
            print(A()._list)
main()

很久没从python学习了。有人可以向我解释为什么选择选项1后,输入选项2后列表仍为[]吗?

1 个答案:

答案 0 :(得分:2)

因为您要调用其他实例。只需在此处引入变量,您将获得所需的结果。更新的代码是

class A:
    def __init__(self):
        self._list = []

    def addItem(self, x):
        self._list.append(x)

def main():
    a = A()
    while True:
        option = int(input("Enter option: "))
        if option == 1:
            a.addItem("hello")
        if option == 2:
            print(a._list)
main()