python keyworded lambda function
This question already has an answer here:
You are getting this error because kwargs is a dict . In your case, this dict looks like this:
{'key': lambda x: x*x}
So when you iterate over the dict , you are really iterating over the keys, which in the case of kwargs , are strings (and strings are not callable).
If you really want to get at the lambda, then you should access the value within kwargs at that key:
for fart in kwargs:
print(fart)
print(kwargs[fart[](4))
Of course, there's an easier way to do this:
for fart, shart in kwargs.items():
print(fart)
print(shart(4))
kwargs is a dictionary. Iterating on a dictionary gives you the key values.
Whn you iterate, just use items() or values() if you expect lambda functions for all keys:
for fart in kwargs:
print(kwargs[fart](4))
or on values:
for fart in kwargs.values():
print(fart(4))
More reasonably, what you need to call your lambda is to use the key key :
def test1(**kwargs):
print(kwargs["key"](4))
test1(key=lambda x: x*x)
here it prints 16
上一篇: 如何解开python中的键值对?
