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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...