Python 类 和 __init___ 构造函数,如何创建列表变量?

Python classes and the __init___ constructor, how to make a list variable?

您好,我正在创建一个包含购物清单的 class。该代码似乎有效,但我不确定我是否正确执行。我是想把 shopping = [] 放在构造函数中,那有什么作用? 非常感谢

class Shopping:
    def __init__(self, shopping = []): 
        self.__shopping = []

   
    def set_shopping(self, shopping): 
          self.__shopping  = shopping
    def get_shopping(self): 
        return self.__shopping

shoppinglist = Shopping()
shoppinglist = ['apples', 'pears', 'bread']

这是一个例子:

class Shopping:
    def __init__(self, shopping = []): 
        self.__shopping = []
    
    def set_shopping(self, shopping): 
          self.__shopping  = shopping
    
    def get_shopping(self): 
        return self.__shopping
    
    def add_article(self, article): 
          self.__shopping.append(article)

    def get_article(self, index): 
          return self.__shopping[index]

    shoppinglist = Shopping()
    shoppinglist.set_shopping(['apples', 'pears', 'bread'])
    shoppinglist.add_article('oranges')
    shoppinglist.get_article(0) #==> 'apples'
    shoppinglist.get_article(3) #==> 'oranges'