4

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.

1
  • Vegetable shopper RPG - love it! Commented Nov 14, 2013 at 18:55

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

5 Comments

I'll have to research this method to understand it. I haven't seen this yet in the book. However, when I plug it in, I get the same result as before.
Make sure it is part of your Veg class. If you are still seeing <class '__main__.Veg'> in your results, you didn't add it in the correct location and/or did not reload your code.
He shouldn't be using __repr__ for the human readable version of the class; __str__ is reserved for that. __repr__ is reserved for the machine readable version of the class. See docs.python.org/3/reference/…
@jknupp: But when printing the list, the repr() is used automatically. Note that my example creates a reasonable machine representation that could be used to recreate the Veg object.
@MartijnPieters Right, which is why he shouldn't be printing the list when what he really wants is to print its contents.
2

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!')

Comments

1

Your issue is here:

def createVeg():
    name = input('What is the name of the Vegetable? ')
    color = input('What color is the vegetable? ')
    Veg(name, color) # 1
    vegList.append(Veg) # 2
    return

The line I've commented as #1 creates a new instance of a veg object. However, it doesn't do anything with it. It doesn't store it anywhere, or name it, like if you had written a = Veg(name, color). Basically, it creates the object, then forgets about it.

The line I've commented as #2 then appends the Veg CLASS to the list, rather than an instance of the class. This would be like adding the concept of an integer to a list, rather than adding an actual integer of 5.

Try replacing these two lines with...

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

Once you do this, you're still going to want to follow Martijn Pieters' answer to get the object to print correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.