Gre*_*106 4 python class list python-3.x
我是编程和尝试自学的新手.我目前正在尝试学习如何从类构建对象,我想我理解.我当前的任务是将对象添加到列表中并打印该列表.最终,我正在尝试构建一个创建对象的程序,并列出已在编号列表中创建的每个对象,即:
1 - tomato, red
2 - corn, yellow
etc...
Run Code Online (Sandbox Code Playgroud)
首先,我只是想构建这个的基本部分.这是我做的:
# 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!')
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到以下内容:
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!
Run Code Online (Sandbox Code Playgroud)
所以,据我所知,一切都有效,除了打印清单,我无法弄清楚.它似乎是附加列表属性,但不显示对象.我也试过'for'循环,但结果相同.
这一切都按设计工作.该<class '__main__.Veg'>字符串是表示你的Veg类的实例.
您可以通过为类提供__repr__方法来自定义该表示:
class Veg:
# ....
def __repr__(self):
return 'Veg({!r}, {!r})'.format(self.name, self.color)
Run Code Online (Sandbox Code Playgroud)
所有__repr__功能都要返回一个合适的字符串.
使用上面的示例__repr__函数,您的列表将显示为:
[Veg('tomato', 'red'), Veg('corn', 'yellow')]
Run Code Online (Sandbox Code Playgroud)
您确实需要确保实际附加新实例.代替:
Veg(name, color)
vegList.append(Veg)
Run Code Online (Sandbox Code Playgroud)
做这个:
newveg = Veg(name, color)
vegList.append(newveg)
Run Code Online (Sandbox Code Playgroud)