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

问题描述

以下代码片段来自 python 烹饪书,第 3 版。 Chapter 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”?

解决方法

# 使 glProgramUniform 指代方法 meth = self.generic_visit 本身。它引用它的返回值;这将通过为某些 meth 调用 self.generic_visit 获得。