python 装饰器修改调整函数参数

时间:2023-12-31 14:48:44

简单记录一下利用python装饰器来调整函数的方法。现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8。

下面是例子:

 def format_lines():
def make_wrapper(func):
def wrapper(*args, **kwargs):
lines = list(args)[1:]
new_args = list()
for index, line in enumerate(lines):
if isinstance(line,tuple):
for index, l in enumerate(line):
if line > 8 and line <16 :
line = line % 8
elif line == 16:
line = 8
new_args.insert(index,line)
new_args.insert(0,args[0])
return func(*tuple(new_args), **kwargs)
else:
if line > 8 and line <16 :
line = line % 8
elif line == 16:
line = 8
new_args.insert(index,line)
new_args.insert(0,args[0])
return func(*tuple(new_args), **kwargs)
return wrapper
return make_wrapper

注意:wrapper的参数args即实际的lines,修改完后,传递给实际的func函数即可

使用:

class MainCom_Usb_Cmd():
"""atc platform hardware usb cmd """
def __init__(self,ip,port):
self.address = (ip, int(port)) @format_lines()
def turn_on_usb_signal(self,*lines):
"""only turn on usb signal """
if not lines :
lines = range(1,9) while True:
try:
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.address)
break
except Exception, e:
time.sleep(0.1)
continue
try:
is_succeed = True
self.close_usb(lines,is_connect=True)
for line in lines:
retry_count = 0
while retry_count < 3:
self.client.send('SwitchToUSB:::&%d&&&&\n\r' % line)
time.sleep(.2)
data = self.client.recv(1024)
if len(data)>0:
print data
pattern = re.compile(r"CH%d\s+USB\s+sig\s+connect\s+to\s+PCUSB" % line)
match = pattern.search(data)
if match is None:
retry_count = retry_count + 1
else:
break
if retry_count >= 3:
is_succeed = False
except:
traceback.print_exc()
finally:
self.client.close()
return is_succeed @format_lines()
def turn_on_usb_power(self,*lines):
"""only turn on usb power for fastly charging device """ if not lines:
lines = range(1,9) while True:
try:
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.address)
break
except Exception, e:
time.sleep(0.1)
continue
try:
is_succeed = True
self.close_usb(lines,is_connect=True)
for line in lines:
retry_count = 0
while retry_count < 3:
self.client.send('SwitchToDUT5V:::&%d&&&&\n\r' % line)
time.sleep(.2)
data = self.client.recv(1024)
if len(data)>0:
print data
pattern = re.compile(r"CH%d\s+USB\s+POWER\s+connect" % line)
match = pattern.search(data)
if match is None:
retry_count = retry_count + 1
else:
break
if retry_count >= 3:
is_succeed = False
except:
traceback.print_exc()
finally:
self.client.close()
return is_succeed