# coding:utf8

''''''

'''------------------ 基本装饰器 ------------------ Start'''
''' 一般写法'''
'''$$$$$$$$$$$$$$$$$$$$$ Start $$$$$$$$$$$$$$$$$$$$$'''


def hello():
return 'hello world!'


def makeitalic(func):
def wrapped():
return '<i>' + func() + '</i>'

return wrapped


hello = makeitalic(hello) # 此步骤返回 wrapped 变量(wrapped函数,尚未执行),
print hello() # 调用方法后wrapped函数是执行hello()函数,
print hello.__name__ # 而 hello.__name__ 隐性变成wrapped

<!-- more -->
'''
解析:
1、将hello函数当做参数传给makeitalic函数
2、makeitalic中wrapped函数给func()函数结果加上 <i> </i>标签, 返回
3、makeitalic 最终返回的是 return '<i>' + func() + '</i>'
4、makeitalic(func) 被称为装饰器,对hello进行装饰,返回一个变量(函数),赋值给hello
'''
'''$$$$$$$$$$$$$$$$$$$$$ End $$$$$$$$$$$$$$$$$$$$$'''

''' 等价于(语法糖简略写法) '''


def makeitalic(func):
def wrapped():
return '<i>' + func() + '</i>'

return wrapped


@makeitalic
def hello():
return 'hello world'


print hello()

''' --------------------- 一般使用形式 --------------------- Start'''


@decorator
def func():
pass


# 等价于下面的形式:

def func():
pass


func = decorator(func)


# 装饰器可以定义多个,离函数定义最近的装饰器先被调用
@decorator_one
@decorator_two
def func():
pass


# 等价于
def func():
pass
func = decorator_one(decorator_two(func))

''' --------------------- 一般使用形式 --------------------- End'''

'''------------------ 基本装饰器 ------------------ End'''


'''------------------ 对带参数的函数进行装饰 ------------------ Start'''
def makeitalic(func):
def wrapped(*args, **kwargs):
ret = func(*args, **kwargs)
return '<i>' + ret + '</i>'
return wrapped

@makeitalic
def hello(name):
return "hello %s" % name

@makeitalic
def hello_2(name1, name2):
return 'hello %s, %s.' %(name1, name2)

print hello('java')

print hello_2('c++','python')

# 返回值
'''
<i>hello java</i>
<i>hello c++, python.</i>
'''

'''------------------ 装饰器的副作用 ------------------ Start'''


def makeitalic(func):
def wrapped():
return "<i>" + func() + "</i>"
return wrapped


@makeitalic
def hello():
return 'hello world'


print hello.__name__

'''
函数 hello 被 makeitalic 装饰后,它的函数名称已经改变了:
返回:
wrapped
'''
# 修改
from functools import wraps

def makeitalic(func):
@wraps(func) # 加上 wraps 装饰器
def wrapped():
return "<i>" + func() + "</i>"
return wrapped

@makeitalic
def hello():
return 'hello world'

print hello.__name__
'''
'hello'
'''

'''------------------ 装饰器的副作用 ------------------ End'''