擅长:python、mysql、java
<p>你的<code>add_toys</code>方法不好,你没有使用<code>toys</code>参数,它不应该返回任何东西,应该是这样的</p>
<pre><code>class Pet:
# __init__ is OK
def add_toys(self, *toys):
for toy in toys:
if toy not in self.toys:
self.toys.append(toy)
def __str__(self):
if not 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, self.toys)
</code></pre>
<p>像</p>
<pre><code>p = Pet("Foo")
p.add_toys("ball")
p.add_toys("plate", "frisbee")
print(p) # Foo is a Unknown that has the following toys: ['ball', 'plate', 'frisbee']
</code></pre>
<hr/>
<p>您可以直接使用<code>set</code></p>
<pre><code>class Pet:
def __init__(self, name, kind="Unknown"):
self.name = name
self.kind = kind
self.toys = set()
def add_toys(self, *toys):
self.toys.update(toys)
</code></pre>