我是一个编程新手,正在尝试自学编程。我目前正试图学习如何从类中构建对象,并且我认为我已经理解了这个过程。我的当前任务是将对象添加到列表中并打印该列表。最终,我正在尝试构建一个程序,创建一个对象并在编号列表中列出已创建的每个对象,例如:
1 - tomato, red
2 - corn, yellow
etc...
首先,我只是尝试构建它的基本部分。这是我制作的内容:
# 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!')
当我运行这个程序时,会得到以下结果:
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!
据我所知,除了打印列表之外,一切都正常,但我无法解决这个问题。它似乎在添加列表属性,但未显示对象。我还尝试了“for”循环,但结果相同。