简体   繁体   中英

Python class function, can't append to list

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()

Sorry haven't been learning from python that long. Can someone explain to me why after option 1 is chosen, the list is still [] after i enter option 2?

Because you are calling different instances. Just introduce a variable here and you would get your desired result. The updated code is

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM