python - 如何在以下代码中为每个 while 循环采用不同的 r 值?python
问题描述
import random
class check_error:
def __init__(self,firstbyte=bytearray(b'\x15\x04\xA5')) :
r=random.choice (firstbyte)
self.r=r
def pocket_data(self):
print("I am sending request for NBP/SpO2 datas")
r=self.r
while True:
print("blala")
r=self.r
print(r)
try:
if int("{:02x}".format(r))==15:
print("Negative Acknowledgment.Error occured during data transmission to device.I am sending the datas again... ")
continue
elif r==4:
print("Host does not have the capability to respond to the request,it only supports a subset of the protocol")
continue
except:
print("done")
break
s=check_error()
print(s.pocket_data())
如果选择的元素是 x15 或 x04,则循环变得无穷无尽,但我想做的是选择 bytearray 的不同元素,直到选择的元素是 xA5。
解决方案
初始化类时,r
设置为random.choice (firstbyte)
. 请注意,这永远不会改变;您设置 的值r
,然后分配self.r = r
,然后您再也不会更改self.r
。
如果您想r
继续滚动随机数,您需要做的是保存firstbyte
到类中的变量中 - 例如:
def __init__(self,firstbyte=bytearray(b'\x15\x04\xA5')) :
self.firstbyte = firstbyte
r=random.choice (firstbyte)
self.r=r
然后,在循环内部,继续以与构造函数中相同的方式生成随机数:
while True:
self.r = random.choice(self.firstbyte)
...
推荐阅读
- c++ - 当我使用整数编码读取 mp3 时,libmpg123 强制浮点输出
- python - 为 contextvars.Context 提供一个 ContextManager
- reactjs - 使用参数 (computedFn) 和 TypeScript 计算的 Mobx - 这是什么?
- mysql - SQL Count 每次行等于列
- visual-studio-code - 如何更改 VSCode 中的“范围”指示符?
- java - 如何在适配器上制作 2 个数组列表,以适应一个 API?
- c++ - 在 C++ 中跨越动态分配的二维数组时的侵入值/地址
- jquery - JQuery 文档就绪效率
- excel - 从字符串中提取 Excel VBA 文件名
- python - 在嵌入 C++ 程序的 python 脚本中使用 matplotlib 时出错