简体   繁体   中英

Why does appending to the list of a class instance and then returning it from a method result in an empty list?

Why does the app method of the b class not work? I want to append 5 to mylist .

class a:
    def __init__(self):
        self.mylist = []
    
class b:
    def app(self):
        a().mylist.append(5)
        return a().mylist

You do append 5 to the list of an a instance. But then you throw it away and create another a instance with a new empty list again.

You need to keep the first a instance and return its list:

def app(self):
    my_a = a()
    my_a.mylist.append(5)
    return my_a.mylist

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