包含调用该参数函数及其余功能的新函数
的一种函数。 @decorator_name
的方式使用def hello(): print("hello world!!!")
hello()
功能而不直接修改其定义def log(func): """print function name before it's called""" def wrapper(*args, **kw): # 闭包,实现装饰器的基础 print('call %s():\n' % func.__name__, end=" ") return func(*args, **kw) # 传递给wrapper的参数最后传递给了func return wrapper @log def hello(): print("hello world!!!") hello()
输出:python
call hello(): hello world!!!
hello = log(hello) # 此调用的执行效果等效于 log.func = hello, hello = log.wrapper
class Student(object): # @property # 做用是把类方法转换成类属性 # def score(self): # return self._score # 替换 @property的效果 def score(self): return self._score score = property(score) @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value a = Student() a.score = 60 a.score
输出:闭包
60