Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating Python objects, and using lists

I'm very new to programming and trying to teach myself. I'm currently trying to learn how to build objects from classes, which I think I understand. My current task is to add the object into a list and print that list. Ultimately I'm trying to build a program that creates an object and lists each object that has been created in a numbered list, i.e.:

1 - tomato, red
2 - corn, yellow
etc...

So to begin, I'm just trying to build the basic part of this. Here is what I made:

# Builds objects on instantiation for a vegetable and color
class Veg:
    def __init__(self, name, color):
        self.name = name
        self.color = color
        print('You have created a new', self.color, self.name, end='.\n')

# Function to create a new vegetable and store it in a list
def createVeg():
    name = input('What is the name of the Vegetable? ')
    color = input('What color is the vegetable? ')
    Veg(name, color)
    vegList.append(Veg)
    return

# Initialize variables
vegList = []
choice = 'y'

# Main loop
while choice == 'y':
    print('Your basket contains:\n', vegList)
    choice = input('Would you like to add a new vegetable? (y / n) ')
    if choice == 'y':
        createVeg()
    if choice == 'n':
        break

print('Goodbye!')

When I run this, I get the following:

Your basket contains:
 []
Would you like to add a new vegetable? (y / n) y
What is the name of the Vegetable? tomato
What color is the vegetable? red
You have created a new red tomato.
Your basket contains:
 [<class '__main__.Veg'>]
Would you like to add a new vegetable? (y / n) y
What is the name of the Vegetable? corn
What color is the vegetable? yellow
You have created a new yellow corn.
Your basket contains:
 [<class '__main__.Veg'>, <class '__main__.Veg'>]
Would you like to add a new vegetable? (y / n) n
Goodbye!

So, from what I can tell, everything works except for printing the list, which I can not figure out. It seems to be appending the list propery, but not displaying the object. I've also tried a 'for' loop, but got the same result.

like image 339
Gregory6106 Avatar asked Jan 13 '23 22:01

Gregory6106


2 Answers

It is all working as designed. The <class '__main__.Veg'> string is the representation of your Veg class instances.

You can customize that representation by giving your class a __repr__ method:

class Veg:
    # ....

    def __repr__(self):
        return 'Veg({!r}, {!r})'.format(self.name, self.color)

All the __repr__ function has to do is return a suitable string.

With the above example __repr__ function, your list would instead look like:

[Veg('tomato', 'red'), Veg('corn', 'yellow')]

You do need to make sure you actually append your new instance. Instead of:

Veg(name, color)
vegList.append(Veg)

do this:

newveg = Veg(name, color)
vegList.append(newveg)
like image 159
Martijn Pieters Avatar answered Jan 17 '23 17:01

Martijn Pieters


The problem is in the lines

Veg(name, color)
vegList.append(Veg)

What you're doing here is creating a new Veg but not assinging anything to it. Then you're appending Veg the type to a list. Also, you need to tell Python how to print you Veg objects in a human readable way by adding the __str__ method to your class. Lastly, if you print a list directly (print vegList) you'll get the machine readable representation of the contents of the list, which isn't what you want. Iterating over the list's elements and printing them directly will work.

Here's a working version with the requisite changes:

# Builds objects on instantiation for a vegetable and color
class Veg:
    def __init__(self, name, color):
        self.name = name
        self.color = color
        print('You have created a new', self.color, self.name, end='.\n')

    def __str__(self):
        return 'One {} {}'.format(self.color, self.name)

# Function to create a new vegetable and store it in a list
def createVeg():
    name = input('What is the name of the Vegetable? ')
    color = input('What color is the vegetable? ')

    vegList.append(Veg(name, color))
    return

# Initialize variables
vegList = []
choice = 'y'

# Main loop
while choice == 'y':
    print('Your basket contains:\n')
    for veg in vegList:
        print(veg)
    choice = input('Would you like to add a new vegetable? (y / n) ')
    if choice == 'y':
        createVeg()
    if choice == 'n':
        break

print('Goodbye!')
like image 32
jeffknupp Avatar answered Jan 17 '23 17:01

jeffknupp