I tried to execute this part of code:
def func():
print 'function is being called'
mapp=dict{'first': 'value_1','second':func()}
print mapp.get('first')
I expected to see output as 'value_1'
, but the function is also getting executed even though I am not explicitly calling it.
Output:
enter image description here
How to make this dictionary so that, the function will not be executed when not called explicitly.
CodePudding user response:
func()
will call the function. If you want to get the function as a first-class object, then just use func
. Example:
mapp = {'first': 'value_1', 'second': func}
CodePudding user response:
Put the function name in the dictionary without the parentheses, just the function name: mapp=dict{'first': 'value_1', second':func}
.
CodePudding user response:
def func():
print('function is being called')
def func_2(msg='No comment'):
print(msg)
mapp = {'first': 'value_1', 'second': func, 'third': func_2, 'fourth': func_2}
print(mapp.get('first'))
mapp.get('second')()
mapp.get('third')()
mapp.get('fourth')('Yes, I have a lot to say')
Output
value_1
function is being called
No comment
Yes, I have a lot to say