I am aware of *
operator but this one does not seem to work. I basically want to unpack this list consisting of tuple pairs:
sentence_list = [('noun', 'I'), ('verb', 'kill'), ('noun', 'princess')]
Consider my class Sentence:
class Sentence(object):
def __init__(self, subject, verb, object):
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
Now I create an object called test_obj and when I try to unpack sentence_list it does not seem to work:
test_obj = Sentence(*sentence_list)
When I test it with nose.tools
using:
assert_is_instance(test_obj, Sentence)
I get this:
TypeError: __init__() takes exactly 4 arguments (3 given)
But when I change it to:
test_obj = Sentence(('noun', 'I'), ('verb', 'kill'), ('noun', 'princess'))
It passes the test. What am I doing wrong?
Your code works just fine, provided you actually pass in a list of 3 elements:
>>> 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)
Note the error message here; __init__
takes four arguments, including self
.
Ergo, it is your sentence_list
value that is at fault here, not your technique.