【发布时间】:2017-01-11 23:24:44
【问题描述】:
我正在研究一个涉及创建和使用具有多种方法的类的 python 评估。我不会发布整个内容,因为如果我展示我正在尝试做的事情的示例,那么指出我的问题会更简单。
class Fruit(self,color,name):
def __init__(self, color, name):
self.color = color
self.name = name
def return_list(self, index):
print fruit_list[index]
fruit_list = []
fruit_1 = Fruit("red", "apple")
fruit_list.append(fruit_1.color)
fruit_list.append(fruit_1.name)
所以上面的代码有效。我的问题是让 return_list 在课堂外使用时起作用,如下所示:
fruit_choice = int(raw_input("What fruit would you like?"))
Fruit.return_list(fruit_choice)
基本上我正在尝试创建一个方法,当被调用时,在列表中的索引处输出项目,该索引由用户输入指定(即fruit_choice = 0,打印的项目是列表的第一个元素。)
我对类有基本的了解,但是像 return_list 这样有点模糊的方法有点不直观。我得到的错误信息:
Fruit.return_list(fruit_choice)
TypeError: unbound method return_list() must be called with Fruit instance as first argument (got int instance instead)
我知道如果我让代码工作,如果输入为 0 而不是“red,”apple,则输出将是“red”,但这是另一个问题。
如果有人能指出我在创建/调用 return_list 方法时做错了什么,请感谢。
【问题讨论】:
-
Fruit.return_list(fruit_choice)应该是fruit_1.return_list(fruit_choice)。您必须将该方法附加到一个实例(这就是消息所说的)。但在那之后它就不起作用了,因为fruit_list不是该类的成员(这不应该是因为您不希望水果对象中有水果列表!)。多学习 OO 编程...
标签: python list python-2.7 class methods