繁体   English   中英

使用列表作为可用对象实例化一个类

[英]Instantiate a class with list as useable object

我是 OOP 的新手,因此可能会在 Python 中以错误的方式解决这个问题。 我想要做的是用其他对象的列表作为参数实例化一个类。 然后我希望能够遍历该列表,调用第一个对象的一些参数。 问题是当我实例化第二个类时,列表参数被简化为单个对象 - 这意味着我无法对其进行迭代。 这是有道理的,但我不知道如何解决它。

下面是一个例子:

#create a class of Goods with attributes: description and price
class Goods:
    def __init__(self, desc, price):
        self.desc = desc
        self.price = price

#create a class of Shelf, which is a list of Goods
class Shelf:
    def __init__(self, stuff):
        self.stuff = stuff

#write a method for Shelf that prints just the descriptions of everything on the shelf (this is what won't work)
    def print_stuff_descriptions(self):
        return([self[i].desc for i in range(len(self))])

#create two Goods:
icecream = Goods('Icecream', 10)
butter = Goods('Butter', 5)

#now create a Shelf containing those two Goods
isle_1 = Shelf([icecream, butter])

#Now i try to use the method for printing descriptions
print(isle_1.print_stuff_descriptions())

这会引发错误: TypeError: object of type 'Shelf' has no len() ,这是有道理的,因为print(isle_1)给出: <__main__.Shelf object at 0x0124ECB0>即没有长度的单个对象。

我可以通过执行以下操作(而不是创建 Shelf 对象)来解决这个问题:

#create a list of the Goods
isle_1 = [icecream, butter]

#create a list of the descriptions
isle_1_stuff_descriptions = [isle_1[i].desc for i in range(len(isle_1))]

#print the result
print(isle_1_stuff_descriptions)
['Icecream', 'Butter']

这一切都是有道理的,但我希望能够根据以下条件执行诸如运行条件之类的操作:

if 'Icecream' in isle_1.print_stuff_descriptions:

相反,我必须创建变量,然后创建描述列表,然后在该新变量上运行条件。

if 'Icecream' in isle_1_stuff_descriptions:

这看起来非常麻烦,而且我认为 OOP 的目的是让它变得更优雅。 这是这样做的方法,还是有办法在 OOP 中做到这一点?

您没有在print_stuff_descriptions使用self.stuff 它应该是:

    def print_stuff_descriptions(self):
        return([self.stuff[i].desc for i in range(len(self.stuff))])

或更简单地说:

    def print_stuff_descriptions(self):
        return [x.desc for x in self.stuff]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM