@TOC
装饰器:用一个函数去装饰别的函数或类,为其提供横切关注功能。
横切关注功能-跟正常的业务逻辑没有必然联系的功能
题目一:设计一个装饰器函数,如果被装饰的函数返回字符串则将字符串每个单词首字母大写
方法一:使用 字符串.title()
from functools import wraps
str1 = 'this is string example....wow!!!'
# 法一:使用 字符串.title()
def my_uper(f):
@wraps(f)
# 是一个带参数的装饰器。
# 作用:a,保留被装饰的函数的名字--> __name__
# b.可以取消装饰,使用原函数--> __wrapped__()
def new_f(*args, **kwargs):
result = f(*args, **kwargs)
if isinstance(result, str):
return result.title()
return new_f
@my_uper
def abc():
a = 'this is string example....wow!!!'
return a
print(abc()) #This Is String Example....Wow!!!
print(abc.__wrapped__()) #取消装饰器,使用原函数 #this is string example....wow!!!
方法二:capwords(字符串)
from functools import wraps
from string import capwords
# 法二:capwords(字符串)
def my_uper2(f):
@wraps(f)
def new_f(*args, **kwargs):
result = f(*args, **kwargs)
if isinstance(result, str):
return capwords(result)
return new_f
@my_uper2
def abc2():
a = 'this is string example....wow!!!'
return a
print(abc2()) #This Is String Example....wow!!!
print(abc2.__wrapped__()) #this is string example....wow!!!
方法三:循环+split+join :单词之间以空格隔开的情况使用
from functools import wraps
def my_uper3(f):
@wraps(f)
def new_f(*args, **kwargs):
result = f(*args, **kwargs)
if isinstance(result, str):
return ' '.join([word[0].upper() + word[1:] for word in result.split()])
return new_f
@my_uper3
def abc3():
a = 'this is string example....wow!!!'
return a
print(abc3()) #This Is String Example....wow!!!
print(abc3.__wrapped__()) #this is string example....wow!!!
方法四:正则表达式+join :单词之间以单词边界隔开的情况
from re import *
from functools import wraps
from re import findall
def my_uper4(f):
@wraps(f)
def new_f(*args, **kwargs):
result = f(*args, **kwargs)
if isinstance(result, str):
return ' '.join([word[0].upper() + word[1:] for word in findall(r'(?i)\b[a-z]+\b', result)])
return new_f
@my_uper4
def abc4():
a = 'this is string example....wow!!!'
return a
print(abc4()) #This Is String Example Wow
print(abc4.__wrapped__()) #this is string example....wow!!!
题目二: 写一个装饰器,如果字符串超过了指定长度,做截断,补上省略号
from functools import wraps
def truncate_string(*,length):
def decorate(f):
@wraps(f)
def new_f(*args,**kwargs):
result=f(*args,**kwargs)
if len(result)> length:
return result[:length]+'...'
return result
return new_f
return decorate
@truncate_string(length=10)
def print_str2():
return 'hello,world! hello,world! hello,world! hello,world!'
# return 'helloworld'
print(print_str2()) #hello,worl...