Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
938 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...