简体   繁体   中英

Instantiate a class with list as useable object

I am new to OOP and thus possibly going about this the wrong way in Python. What I am trying to do is instantiate a class with a list of other objects as an argument. I then want to be able to iterate over that list calling some argument of the first object. The problem is when i instantiate the second class the list argument is reduced to a single object - meaning I cannot iterate over it. This makes sense but I don't know how to get around it.

Here is an example:

#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())

This throws the error: TypeError: object of type 'Shelf' has no len() , which makes sense as print(isle_1) gives: <__main__.Shelf object at 0x0124ECB0> ie a single object with no length.

I can get around this by doing the following (instead of creating the Shelf object):

#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']

This all makes sense, but I would like to be able to do things like run conditions based on:

if 'Icecream' in isle_1.print_stuff_descriptions:

Instead I have to create the variable and then create the list of descriptions and then run the conditional on that new variable.

if 'Icecream' in isle_1_stuff_descriptions:

This seems extremely cumbersome and is the sort of thing I thought OOP was meant make more elegant. Is this the way to do it, or is there a way to do this in OOP?

You're not using self.stuff in print_stuff_descriptions . It should be:

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

or more simply:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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