Python 3.x 代码优化->将两个函数合并到一个函数中

Python 3.x 代码优化->将两个函数合并到一个函数中,python-3.x,Python 3.x,对于我来说,现在开始编程还很早,希望能从以下简单代码中得到一些帮助: import time start_time = time.time() progress_time = 0 attempts_counter = 0 penetration_time = 2 def force(): with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock: **while

对于我来说,现在开始编程还很早,希望能从以下简单代码中得到一些帮助:

import time
start_time       = time.time()
progress_time    = 0
attempts_counter = 0
penetration_time = 2

def force():
    with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock:
            **while progress_time < penetration_time:**
                attempts_counter += 1
                **tempKey = test.random_key(8)** 
                request = UDS()/UDS_SA(securityAccessType=[0x02], securityKey = tempKey)
                response = sock.sr1(request, timeout=0.3, verbose=False)
                print (request,response)
            progress_time  = int(time.time() - start_time)

def Memory():
    with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock:
            **for tempKey in range (0x0F):**
                attempts_counter += 1
                request = UDS()/UDS_SA(securityAccessType=[0x02], securityKey = tempKey)
                response = sock.sr1(request, timeout=0.3, verbose=False)
                print (request,response)
            progress_time  = int(time.time() - start_time)
这两个函数之间的唯一区别是while、for循环和赋值tempkey。所以我想在我的类中将两者合并到一个函数中。我尝试为循环后的代码部分创建一个函数,然后在循环中调用它,但没有成功

您是否尝试过以下方法:

attempts_counter = 1

def process(tempKey, sock):
  attempts_counter += 1
  request = UDS()/UDS_SA(securityAccessType=[0x02], securityKey = tempKey)
  response = sock.sr1(request, timeout=0.3, verbose=False)
  print(request, response)

def force():
    with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock:
            while progress_time < penetration_time:
                tempKey = test.random_key(8)
                process(tempKey, sock)
            progress_time  = int(time.time() - start_time)

def Memory():
    with ISOTPSocket(iface0, SID, DID, basecls=UDS, padding=True) as sock:
            for tempKey in range (0x0F):
                process(tempKey, sock)
            progress_time  = int(time.time() - start_time)

您还可以共享您尝试过但未运行的代码段吗?