@score.setter defscore(self, value): ifnot isinstance(value, int): raise ValueError('score must be an integer!') if value < 0or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value s = Student() s.score = 60 s.score
deftypeassert(*ty_args,**ty_kargs): defdecorator(func): sig = signature(func) btypes = sig.bind_partial(*ty_args,**ty_kargs).arguments defwrap(*args,**kwargs): for name,obj in sig.bind(*args,**kwargs).arguments.items(): if name in btypes: ifnot isinstance(obj,btypes[name]): raise TypeError('"%s" must be "%s"' %(name,btypes[name])) return func(*args,**kwargs) return wrap return decorator
if n <= 1: return1 else: return fibonacci(n - 1) + fibonacci(n - 2)
if __name__ == '__main__': print(fibonacci('a')) #Traceback (most recent call last): # File "/home/sunyan/PycharmProjects/sunyan/sunyan.py", line 37, in # print(fibonacci('a')) # File "/home/sunyan/PycharmProjects/sunyan/sunyan.py", line 12, in wrap # raise TypeError('"%s" must be "%s"' %(name,btypes[name])) #TypeError: "n" must be ""
这里我们输入了字符型变量,但是要求输入是一个 int 变量,所以程序报错,提示应该输入 int 类型。
属性可修改的函数装饰器
下面是一个测试函数运行时间的装饰器,并记录进入日志里面。
1 2 3 4 5 6 7 8 9 10 11
import time import logging logging.basicConfig(level=logging.INFO) defruntime(func): @wraps(func) defwrap(*args, **kwargs): start = time.time() used = time.time()-start msg = '%s used time: %s' %(func.__name__,used) logging.info(msg) return wrap
deftypeassert(*ty_args,**ty_kargs): defdecorator(func): sig = signature(func) btypes = sig.bind_partial(*ty_args,**ty_kargs).arguments @wraps(func) defwrap(*args,**kwargs): for name,obj in sig.bind(*args,**kwargs).arguments.items(): if name in btypes: ifnot isinstance(obj,btypes[name]): raise TypeError('"%s" must be "%s"' %(name,btypes[name])) return func(*args,**kwargs) return wrap return decorator
import time import logging logging.basicConfig(level=logging.INFO) defruntime(func): @wraps(func) defwrap(*args, **kwargs): start = time.time() res = func(*args, **kwargs) used = time.time()-start msg = '%s used time: %s' %(func.__name__,used) logging.info(msg) return res return wrap