[英]The lambda function does not return value
The lambda function does not return the desired value to me I sent lambda x: x * 3.87 and I get ₪ 50 The problem is that x does not get the value 50 so lambda does not work I would love to help how I get the value ₪ 193.50。
问题在这里c('convert')(lambda x: x*3.87, '₪')
def make_currency(val, sym):
def dispatch(message):
if message == 'get_value':
def get_value(msg):
if msg == 'amount':
return val
elif msg == 'symbol':
return sym
return get_value
if message == 'set_value' or message == 'convert':
def set_value(msg, value):
nonlocal val
nonlocal sym
if msg == 'amount':
val = value
elif msg == 'symbol'or message == 'convert':
sym = value
return set_value
return '{0}{1}'.format(sym,val)
return dispatch
c = make_currency(10.50,'$')
print(c('get_value')('amount'))
print(c('get_value')('symbol'))
c('set_value')('amount',50)
print(c('get_value')('amount'))
print(c('str'))
c('convert')(lambda x: x*3.87, '₪')
print(c('str'))
我的 output:
10.5
$
50
50 美元
₪50
output 应该是:
10.5
$
50
50 美元
₪193.50
您缺少处理lambda
的分支。
lambda
只是匿名的一行 function 所以你需要像其他任何 function 一样调用它。
def make_currency(val, sym):
def dispatch(message):
if message == 'get_value':
def get_value(msg):
if msg == 'amount':
return val
elif msg == 'symbol':
return sym
return get_value
if message == 'set_value' or message == 'convert':
def set_value(msg, value):
nonlocal val
nonlocal sym
if msg == 'amount':
val = value
elif msg == 'symbol' or message == 'convert':
sym = value
# this will handle the lambda assigned to msg
if message == 'convert':
val = msg(val)
return set_value
return '{0}{1}'.format(sym,val)
return dispatch
c = make_currency(10.50,'$')
print(c('get_value')('amount'))
print(c('get_value')('symbol'))
c('set_value')('amount',50)
print(c('get_value')('amount'))
print(c('str'))
c('convert')(lambda x: x*3.87, '₪')
print(c('str'))
话虽如此,您确实应该为此使用类,因为大多数人会发现这种情况下的闭包非常令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.