我知道*
运营商,但这个似乎不起作用。我基本上想要解压缩包含元组对的列表:
sentence_list = [('noun', 'I'), ('verb', 'kill'), ('noun', 'princess')]
考虑我的课句子:
class Sentence(object):
def __init__(self, subject, verb, object):
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
现在我创建一个名为 test_obj 的对象,当我尝试解压 sentence_list 时,它似乎不起作用:
test_obj = Sentence(*sentence_list)
当我使用nose.tools
使用
assert_is_instance(test_obj, Sentence)
我明白了:
TypeError: __init__() takes exactly 4 arguments (3 given)
但是当我改为:
test_obj = Sentence(('noun', 'I'), ('verb', 'kill'), ('noun', 'princess'))
通过测试。我做错了什么?
答案 0 :(得分:1)
您的代码工作正常,提供您实际传递了3个元素的列表:
>>> class Sentence(object):
... def __init__(self, subject, verb, object):
... self.subject = subject[1]
... self.verb = verb[1]
... self.object = object[1]
...
>>> sentence_list = [('noun', 'I'), ('verb', 'kill'), ('noun', 'princess')]
>>> Sentence(*sentence_list)
<__main__.Sentence object at 0x10043c0d0>
>>> del sentence_list[-1]
>>> Sentence(*sentence_list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 4 arguments (3 given)
请注意此处的错误消息; __init__
需要四个参数,包括self
。
因此,这是你的sentence_list
值,而不是你的技术。