您好,我正在创建一个包含购物清单的课程。该代码似乎有效,但我不确定我是否正确执行。我是否打算将 Shopping = [] 放入构造函数中,那有什么作用?提前谢谢了class Shopping: def __init__(self, shopping = []): self.__shopping = [] def set_shopping(self, shopping): self.__shopping = shopping def get_shopping(self): return self.__shoppingshoppinglist = Shopping()shoppinglist = ['apples', 'pears', 'bread']
1 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
这是一个例子:
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'
添加回答
举报
0/150
提交
取消