简体   繁体   中英

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

The following code snippet is from python cook book, 3rd Ed. 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__))

As I comment in the code, I have two questions about this line:

meth = self.generic_visit # this is the line that I have problem with
  1. Why self.generic_visit is parameterless?
  2. more important, generic_visit does nothing but raising a RuntimeError, how come it returned something and assigned to "meth"?

meth = self.generic_visit makes meth refer to the method self.generic_visit itself . It does not refer to its return value; that would be obtained by calling meth(x) for some x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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