我有问题,通过一个论点循环,只是显示“猫”的论点。请记住,我正在向空列表中添加项目自身项目. 我还使用showAllFormatted函数格式化数据。你知道吗
我试着循环然后用“return”AllItems.ShowAllFormatted文件(i.cat)“但在将项目添加到空列表后没有显示结果。你知道吗
class AllItems:
def __init__(self, cat,comment, worth, amount):
self.cat = cat
self.comment= comment
self.worth = worth
self.amount = amount
def ShowAllFormatted(self):
print('{:>10}:>10}{:>10}{:>10}'.format(self.cat,
self.comment,self.worth,self.amount))
class Collection:
def __init__(self):
self.an_item = []
def add_item(self):
item = AllItems(cat, comment, worth,amount)
self.item.append(item)
def ShowAllItems(self):
for i in self.an_item:
AllItems.ShowAllFormatted(i)
return i
def showAllCat(self):
for item in self.an_item:
return item.cat
这是你的代码的一个版本。。。它甚至可以做你想做的事:
您可以使用以下方法进行测试:
这里发生了很多事情:
AllItems
类的名称改为Item
,因为它似乎想要表示一个单独的东西(来自您编写的__ini__()
)。你知道吗ShowAllFormatted
方法的名称,因为类的每个实例(self
,基本上)只需要担心一件事:本身。它不知道/不在乎成为收藏的一部分。你知道吗Collection
类中的add_item
方法不接受任何参数,因此我添加了它们。现在它可以用一些数据实例化Item
类的实例。你知道吗ShowAllCat
,因为我不确定它应该做什么。可以将cat名称作为参数,然后使用该cat循环项目,并调用它们的show_formatted
方法?差不多吧。但是您不需要将任何内容传递给show_formatted
,它现在不需要任何其他参数(但是它可以控制这些内容的打印方式)。你知道吗我修复了一些其他的东西,并使用了更多的python名称(大写字母表示类,小写字母表示其他所有内容)。但其余大部分都没有改变。你知道吗
别忘了给所有类和方法添加docstring!你知道吗
我想你在构造器中的意思是
self.category = cat
。你知道吗相关问题 更多 >
编程相关推荐