python控制参数类型

python的变量可以赋值成任意类型,好随意

在pyExcelerator的第三方模块中,发现了使用装饰器限制函数传入参数类型的代码,记录一下,作为以后的参考:

def accepts(*types):
    #print types
    def check_accepts(f):
        assert len(types) == f.func_code.co_argcount
        def new_f(*args, **kwds):
            for (a, t) in zip(args, types):
                assert isinstance(a, t), \
                       "arg %r does not match %s" % (a,t)
            return f(*args, **kwds)
        new_f.func_name = f.func_name
        return new_f
    return check_accepts

@accepts(object, int)
  def set_width(self, value):
      self.__width_twips = value & 0xFFFF

def get_width(self):
      return self.__width_twips

width = property(get_width, set_width)


检查返回参数
def returns(rtype):
    def check_returns(f):
        def new_f(*args, **kwds):
            result = f(*args, **kwds)
            assert isinstance(result, rtype), \
                   "return value %r does not match %s" % (result,rtype)
            return result
        new_f.func_name = f.func_name
        return new_f
    return check_returns

猜你喜欢

转载自chenying.iteye.com/blog/2390324