包含調用該參數函數及其餘功能的新函數
的一種函數。 @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