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?
-
You are passing in a list of two elements, not 3, to get that exception.Martijn Pieters– Martijn Pieters2014年04月28日 19:09:55 +00:00Commented Apr 28, 2014 at 19:09
1 Answer 1
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.
9 Comments
sentence_list is in your test. It is not a list with enough elements.sentence_list = [('noun', 'I'), ('verb', 'kill'), ('noun', 'princess')] like I wrote before. My test file is something like this: from nose.tools import * import p sentence_list = [('noun', 'I'), ('verb', 'kill'), ('noun', 'princess')] def test_parse_subject_class(): test_obj = p.Sentence(*sentence_list) assert_is_instance(test_obj, p.Sentence) assert_equal(test_obj.subject, 'I') Where p is other module where the actual code is. I'm using nosetests to test it.sentence_list then, because the only way you are getting your exception is if sentence_list contains two and not 3 elements. Add a print statement just before invoking Sentence(*sentence_list) (making sure you run nose -s so stdout is not being captured) and see what is being printed.Explore related questions
See similar questions with these tags.