且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

最Pythonic的方法来进行输入验证

更新时间:2023-11-25 13:15:04

我喜欢装饰器,以将检查与其余输入处理分开.

I like decorators to separate the checking from the rest of the input handling.

#!/usr/bin/env python

def repeatOnError(*exceptions):
  def checking(function):
    def checked(*args, **kwargs):
      while True:
        try:
          result = function(*args, **kwargs)
        except exceptions as problem:
          print "There was a problem with the input:"
          print problem.__class__.__name__
          print problem
          print "Please repeat!"
        else: 
          return result
    return checked
  return checking

@repeatOnError(ValueError)
def getNumberOfIterations():
  return int(raw_input("Please enter the number of iterations: "))

iterationCounter = getNumberOfIterations()
print "You have chosen", iterationCounter, "iterations."

装饰器或多或少是现有功能(或方法)的包装.它获取现有功能(在其@decorator指令下方表示),并为其返回替换".在我们的案例中,此替换在循环中调用原始函数,并捕获在此过程中发生的任何异常.如果没有异常发生,则只返回原始函数的结果.

A decorator is more or less a wrapper for an existing function (or method). It takes the existing function (denoted below its @decorator directive) and returns a "replacement" for it. This replacement in our case calls the original function in a loop and catches any exception happening while doing so. If no exception happens, it just returns the result of the original function.