Skip to main content
 首页 » 编程设计

Python:如何将对象转换为整数

2024年12月31日10mate10pro

我正在我的 Raspberry Pi 3 B+ 上用 Python 3.5.3 创建一个程序来连接我汽车的 OBDII 端口。通过蓝牙正确建立连接,当按预期使用 Python-OBD 库时,数据读取正确,但不幸的是,当创建这个库时,它会自动在 Pint 库的末尾添加一个单元。

我正在尝试转换如下所示的响应:

1689.34 rotations per minute 

只是 float 部分:

1689.34 

所以我可以随着时间的推移将它们相互比较。

我得到的错误如下:

TypeError: int() argument must be a string, a bytes-like object, or a number, not 'OBDresponse' 

我试过的代码是:

rpm1 = connection.query(rpm_sensor) 
 
int(rpm1) 

有什么想法可以帮助解决这个问题吗?

请您参考如下方法:

如果你只想要数字,试试这个:

val = rpm1.value 
 
print(val.magnitude) 

或者:

print(rpm1.value.magnitude) 

如果你想要单位那么:

print(val.units) 

如果您阅读 documentation for OBDresponse ,然后您会看到 response.value 返回一个 Pint 对象。然后,您可以查看 Pint 类的文档,了解如何分别访问数字和单位。

你应该能够从那里处理它。