问题
I have a function, which puts data into a database, called new_item()
:
def new_item(self, item, **optional):
After sending a web form, a function should check the user input and then use this function to put the user input into the database (I'm using Flask, function name is add_item()
):
Market.new_item([request.form['title'],
session.get('user_id'),
request.form['category']],
{'desc': request.form['desc'],
'place': request.form['place'],
'price': request.form['price'],
'ono': ono})
But I get this error:
File X, line 99, in add_item
'ono': ono})
TypeError: new_item() takes exactly 2 arguments (3 given)
Fur debugging I print this statement right before I call the function add_item
. Console output is:
([u'iPhone 5', '791465667539154', u'2'],
{'price': u'99', 'place': u'Bossental', 'ono': True, 'desc': u'My brand new iPhone'})
I really don't know what's wrong. I never worked with **kwargs
before; is that related to the problem?
回答1:
You are providing three arguments to the function:
- The implicit
self
argument,Market
; - The list, which will be
item
; and - The dictionary, which causes the problem.
**optional
is a special argument, that packs all of the keyword arguments not already specified into a dictionary, accessible within the function as optional
(by convention, this is usually called kwargs
).
A quick demonstration:
>>> def demo(x, y=None, **kwargs):
print 'x: {0}'.format(x)
print 'y: {0}'.format(y)
print 'kwargs: {0}'.format(kwargs)
>>> demo('foo', y='bar', z='baz')
x: foo # 'x' positional argument
y: bar # 'y' keyword argument
kwargs: {'z': 'baz'} # unspecified keyword arguments
You can unpack a dictionary into keyword arguments with **
too:
>>> demo('foo', **{'y': 'bar', 'z': 'baz'})
x: foo
y: bar
kwargs: {'z': 'baz'}
Therefore if you want to pass the contents of the dictionary into the **optional
argument, you could use that same syntax to unpack the dictionary into keyword arguments:
Market.new_item([request.form['title'],
session.get('user_id'),
request.form['category']],
**{'desc': request.form['desc'],
# ^ note asterisks
'place': request.form['place'],
'price': request.form['price'],
'ono': ono })
回答2:
Market.new_item(
[request.form['title'], session.get('user_id'), request.form['category']],
optional={
'desc': request.form['desc'],
'place': request.form['place'],
'price': request.form['price'],
'ono': ono
}
)
回答3:
If you want to pass keyword arguments then you need to specify the argument name while calling the function.
This link has more info on keyword args
May be you need to modify your code to the following. Then it would work
Market.new_item([request.form['title'], session.get('user_id'), request.form['category']],
'desc' = request.form['desc'],
'place' = request.form['place'],
'price' = request.form['price'],
'ono' = ono)
Hope this helps!
来源:https://stackoverflow.com/questions/24240274/typeerror-functionself-item-kwargs-takes-exactly-2-arguments-3-given