<p>在add_toys中,第一件事是从类级变量中访问toys变量,因此删除该参数,第二件事是<code>add_toys(self,toys)</code>语法不正确,需要像<code>self.add_toys()</code>一样使用它</p>
<pre><code>class Pet(object):
def __init__(self,name=""):
self.name = name
self.kind = "Unknown"
self.toys = []
def add_toys(self):
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 = self.add_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)
</code></pre>
<h2>备选方案:</h2>
<pre><code>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 toys:
if toy not in new_list:
new_list.append(toy)
return new_list
def __str__(self):
toys_list = self.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)
</code></pre>