【问题标题】:Instantiating Python objects, and using lists实例化 Python 对象,并使用列表
【发布时间】:2013-03-02 23:17:30
【问题描述】:

我对编程非常陌生,并试图自学。我目前正在尝试学习如何从类中构建对象,我认为我理解。我当前的任务是将对象添加到列表中并打印该列表。最终,我正在尝试构建一个程序来创建一个对象并列出已在编号列表中创建的每个对象,即:

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”循环,但得到了相同的结果。

【问题讨论】:

  • 蔬菜购物 RPG - 喜欢它!

标签: python list class python-3.x


【解决方案1】:

一切都按设计工作。 &lt;class '__main__.Veg'&gt; 字符串是您的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)

【讨论】:

  • 我必须研究这种方法才能理解它。我还没有在书中看到这个。但是,当我插入它时,我得到的结果和以前一样。
  • 确保它是您的Veg 课程的一部分。如果您仍然在结果中看到&lt;class '__main__.Veg'&gt;,则说明您没有将其添加到正确的位置和/或没有重新加载您的代码。
  • 他不应该将__repr__ 用于该类的人类可读版本; __str__ 是为此保留的。 __repr__ 保留给类的机器可读 版本。见docs.python.org/3/reference/…
  • @jknupp:但是在打印列表时,会自动使用repr()。请注意,我的示例创建了一个合理的机器表示,可用于重新创建 Veg 对象。
  • @MartijnPieters 是的,这就是为什么他不应该打印列表,而他真正想要的是打印其内容。
【解决方案2】:

问题出在线条上

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

您在这里所做的是创建一个新的 Veg,但不为它分配任何东西。然后,您将 Veg 类型 附加到列表中。此外,您需要通过将__str__ 方法添加到您的类来告诉Python 如何以人类可读的方式打印您的Veg 对象。最后,如果您直接打印列表 (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!')

【讨论】:

    【解决方案3】:

    您的问题在这里:

    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 的回答来正确打印对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多