实例化Python对象和使用列表

时间:2013-03-14 14:31:49

标签: python list class python-3.x

我是编程和尝试自学的新手。我目前正在尝试学习如何从类构建对象,我想我理解。我当前的任务是将对象添加到列表中并打印该列表。最后,我正在尝试构建一个创建对象的程序,并列出在编号列表中创建的每个对象,即:

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'循环,但结果相同。

3 个答案:

答案 0 :(得分:6)

这一切都按设计工作。 <class '__main__.Veg'>字符串是Veg类实例的表示

您可以通过为班级__repr__ method

自定义该表示形式
class Veg:
    # ....

    def __repr__(self):
        return 'Veg({!r}, {!r})'.format(self.name, self.color)

所有__repr__函数必须返回一个合适的字符串。

使用上面的示例__repr__函数,您的列表将显示为:

[Veg('tomato', 'red'), Veg('corn', 'yellow')]

您确实需要确保追加新实例。而不是:

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

这样做:

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

答案 1 :(得分:2)

问题出在

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

你在这里做的是创造一个新的蔬菜,但不会给它任何东西。然后,您将Veg 类型附加到列表中。此外,您需要告诉Python如何通过向您的类添加Veg方法以人类可读的方式打印__str__个对象。最后,如果直接打印列表(print vegList),您将获得列表内容的机器可读表示,这不是您想要的。迭代列表的元素并直接打印它们将起作用。

这是一个包含必要更改的工作版本:

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

答案 2 :(得分:1)

您的问题在这里:

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

我被评为#1的行创建了一个veg对象的新实例。但是,它没有做任何事情。它不会将它存储在任何地方,也不会命名,就像你写了a = Veg(name, color)一样。基本上,它会创建对象,然后忘记它。

我被评论为#2的行然后将Veg CLASS附加到列表中,而不是类的实例。这就像将一个整数的概念添加到列表中,而不是添加实际的整数5。

尝试用......替换这两行

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

一旦你这样做,你仍然想要跟随Martijn Pieters&#39;回答让对象正确打印。

相关问题