免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2299 | 回复: 1

条件执行问题 [复制链接]

论坛徽章:
0
发表于 2016-07-19 15:23 |显示全部楼层
大家好,
请教一个关于if elif的问题,代码如下:
import pdb
import types
class Node:
pass

class NodeVisitor:
def visit(self, node):
  print("step in visit")
  pdb.set_trace()
  stack = [node]
  last_result = None
  str1=1
  while stack:
   try:
    last = stack[-1]
    if isinstance(last, types.GeneratorType):
     print("isinstance types")
     pdb.set_trace()
     stack.append(last.send(last_result))
     print("if")
     last_result = None
     test="ok"
     print(test)
    elif isinstance(last, Node):
     print("instance node")
     pdb.set_trace()
     str1+=1
     stack.append(self._visit(stack.pop()))
    else:
     last_result = stack.pop()
   except StopIteration:
    stack.pop()
  return last_result
def _visit(self, node):
  pdb.set_trace()
  methname = 'visit_' + type(node).__name__
  meth = getattr(self, methname, None)
  if meth is None:
   meth = self.generic_visit
  return meth(node)
def generic_visit(self, node):
  raise RuntimeError('No {} method'.format('visit_' + type(node).__name__))

class UnaryOperator(Node):
def __init__(self, operand):
  self.operand = operand

class BinaryOperator(Node):
def __init__(self, left, right):
  self.left = left
  self.right = right

class Add(BinaryOperator):
pass

class Sub(BinaryOperator):
pass

class Mul(BinaryOperator):
pass

class Div(BinaryOperator):
pass

class Negate(UnaryOperator):
pass

class Number(Node):
def __init__(self, value):
  self.value = value

class Evaluator(NodeVisitor):
def visit_Number(self, node):
  pdb.set_trace()
  return node.value
def visit_Add(self, node):
  pdb.set_trace()
  yield (yield node.left) + (yield node.right)
def visit_Sub(self, node):
  pdb.set_trace()
  yield (yield node.left) - (yield node.right)
def visit_Mul(self, node):
  pdb.set_trace()
  yield (yield node.left) * (yield node.right)
def visit_Div(self, node):
  pdb.set_trace()
  yield (yield node.left) / (yield node.right)
def visit_Negate(self, node):
  pdb.set_trace()
  yield - (yield node.operand)

使用pdb调试的时候发现当循环第二次执行到第19行时(if语句中),会继续执行之后的elif:

> <stdin>(7)visit_Add()
(Pdb) n
if
ok
instance node
> <stdin>(22)visit()

代码来自python cookbook第335页
刚学python不久,请教大神这是什么原因?
谢谢!


论坛徽章:
0
发表于 2016-07-20 15:53 |显示全部楼层
问题已解决,是pdb的问题
谢谢大家
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP