사전이 채워지면 피연산자가 인 각 작업을 실행하고 결국 dict[op]
(None
포함)을 호출하고 아무 작업도하지 않기 때문입니다. 모든 출력을 얻을 이유
# N.B.: in case this is not clear enough,
# what follows is the *BAD* code from the OP
# with inline explainations why this code is wrong
dict = {
# executes the function add, outputs the result and assign None to the key '+'
'+': add(part1, part3),
# executes the function sub, outputs the result and assign None to the key '-'
'-': sub(part1, part3),
# executes the function mult, outputs the result and assign None to the key '*'
'*': mult(part1, part3),
# executes the function div, outputs the result and assign None to the key '/'
'/': div(part1, part3)
}
try:
# gets the value at the key "op" and do nothing with it
dict[op]
except KeyError:
default()
, 그리고 아무것도 당신의 try
블록에 변화가 없습니다 : 어떻게됩니까
이다. 당신은 할 수 있습니다
실제로해야 할 일 :
dict = {
'+': add,
'-': sub,
'*': mult,
'/': div
}
try:
dict[op](part1, part3)
except KeyError:
default()
하지만 같은 @christian 현명하게 당신이 변수 이름으로 파이썬 예약 된 이름을 사용해서는 안 제안, 그 문제로 당신을 이끌 수 있습니다. 결과를 반환합니다
d = {
'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'*': lambda x,y: x*y,
'/': lambda x,y: x/y
}
try:
print(d[op](part1, part3))
except KeyError:
default()
하고 그것을
출처
2014-02-23 01:00:12
zmo
메모를 인쇄 : : 그리고 당신이 할 일 다른 개선 I 조언 번 결과를 인쇄하고, 기능 람다를 만드는 것입니다'dict'은 *하지 * 파이썬 키워드 :''dict '이 keyword.kwlist'에 없습니다. 그것은 내장 이름이지만 :''dir (d 내장 (__ builtins __)'에서 dict '. – jfs