簡體   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