📜  装饰器模式 - Python 代码示例

📅  最后修改于: 2022-03-11 14:47:06.286000             🧑  作者: Mango

代码示例1
#decorator pattern uses a decorator that adds a bahavior to an existing function or class  
# e.g. here is aDecorator that is a wrapper function 
def aDecorator(func):     #func is the wrapped function
   def wrapper(*args, **kwargs):
      ret = func(*args, **kwargs)  #get reault of wrapped function
      return f' Decorator has converted result to upper-case: {ret.upper()} '
   return wrapper          #wrapper contains the decoration and result of wrapped function 

@aDecorator                # aDecorator is the wrapper function
def exampleFunction():
   return "basic output"   #lower-case string

print(exampleFunction())   #addDecoration adds note and converts to Upper-case

#Output:
#  Decorator has converted result to upper-case: BASIC OUTPUT