我对编程很陌生,并试图自学。我目前正在尝试学习如何从类构建对象,我认为我理解。我当前的任务是将对象添加到列表中并打印该列表。最终,我正在尝试构建一个程序,该程序创建一个对象并列出已在编号列表中创建的每个对象,即:
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”循环,但得到了相同的结果。