我對編程非常陌生,並且試圖自我教導。我目前正在嘗試學習如何從類構建對象,我認爲這是我理解的。我目前的任務是將該對象添加到列表中並打印該列表。最後,我想建立創建對象,並列出了已編號列表中被創建的每個對象,即程序:實例化Python對象並使用列表
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!
所以,從我可以告訴,一切正常,除了打印清單,我可以不知道。它似乎是追加列表propery,但不顯示對象。我也嘗試了'for'循環,但得到了相同的結果。
蔬菜顧客RPG - 愛它! – Marcin 2013-11-14 18:55:54