我有这个代码:
class Pet(object):
def __init__(self,name=""):
self.name = name
self.kind = "Unknown"
self.toys = []
def add_toys(self,toys):
new_list = []
for toy in self.toys:
if toy not in new_list:
new_list.append(toy)
return new_list
def __str__(self):
toys_list = add_toys(self,toys)
if self.toys == []:
return "{} is a {} that has no toys".format(self.name,self.kind)
else:
return "{} is a {} that has the following toys: {}".format(self.name,self.kind,toys_list)
在函数add_toys()
中,我有返回值new_list。我想在函数中使用该返回值__ str__
并将其定义为toys_list
. 然而,当我写toys_list = add_toys(self, toys)
它说:
add_toys
是一个未定义的变量