通过参数迭代的面向对象编程

2024-10-02 16:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有问题,通过一个论点循环,只是显示“猫”的论点。请记住,我正在向空列表中添加项目自身项目. 我还使用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

Tags: 项目selfan列表returndefcommentitem
2条回答

这是你的代码的一个版本。。。它甚至可以做你想做的事:

class Item:

    def __init__(self, cat, comment, worth, amount):
        self.cat = cat
        self.comment= comment
        self.worth = worth
        self.amount = amount

    def show_formatted(self):
        print('{:>10}{:>10}{:>10}{:>10}'.format(self.cat, 
                                                self.comment,
                                                self.worth,
                                                self.amount,
                                                )
             )
        return None


class Collection:

    def __init__(self):
        self.items = []

    def add_item(self, cat, comment, worth, amount):
        item = Item(cat, comment, worth, amount)
        self.items.append(item)
        return None

    def show_all_items(self):
        for item in self.items:
            item.show_formatted()
        return None

    def get_all_cats(self):
        return [item.cat for item in self.items]

您可以使用以下方法进行测试:

>>> c = Collection()  # Instantiate a Collection object.
>>> c.add_item('C', 'comment', 10, 1000)  # Add an item to it.
>>> c.add_item('C', 'words', 9, 999)  # Add another.
>>> c.show_all_items()
         C   comment        10      1000
         C     words         9       999

这里发生了很多事情:

  • 我将AllItems类的名称改为Item,因为它似乎想要表示一个单独的东西(来自您编写的__ini__())。你知道吗
  • 我更改了ShowAllFormatted方法的名称,因为类的每个实例(self,基本上)只需要担心一件事:本身。它不知道/不在乎成为收藏的一部分。你知道吗
  • Collection类中的add_item方法不接受任何参数,因此我添加了它们。现在它可以用一些数据实例化Item类的实例。你知道吗
  • 我摆脱了ShowAllCat,因为我不确定它应该做什么。可以将cat名称作为参数,然后使用该cat循环项目,并调用它们的show_formatted方法?差不多吧。但是您不需要将任何内容传递给show_formatted,它现在不需要任何其他参数(但是它可以控制这些内容的打印方式)。你知道吗

我修复了一些其他的东西,并使用了更多的python名称(大写字母表示类,小写字母表示其他所有内容)。但其余大部分都没有改变。你知道吗

别忘了给所有类和方法添加docstring!你知道吗

我想你在构造器中的意思是self.category = cat。你知道吗

相关问题 更多 >