繁体   English   中英

python:如果方法只是引发错误,它会返回什么?

[英]python: what does a method return if what it does is just raise error?

以下代码片段来自 python 烹饪书,第 3 版。 第 8.21 章

class NodeVisitor:
  
  def visit(self, node):
    methname = 'visit_' + type(node).__name__
    meth = getattr(self, methname, None)
    if meth is None:
      meth = self.generic_visit # this is the line that I have problem with
    return meth(node)

  def generic_visit(self, node):
    raise RuntimeError('No {} method'.format('visit_' + type(node).__name__))

当我在代码中评论时,我对这一行有两个问题:

meth = self.generic_visit # this is the line that I have problem with
  1. 为什么 self.generic_visit 是无参数的?
  2. 更重要的是, generic_visit除了引发 RuntimeError 什么都不做,它怎么会返回一些东西并分配给“meth”?

meth = self.generic_visit使meth引用方法self.generic_visit本身 引用它的返回值; 这将通过为某些x调用meth(x)来获得。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM