Python用变量类型描述行为



我使用的是第三方python库,即使用ctypes(它使用dll(。我对ctypes不是很熟悉。lib提供了一个类型定义和一个结构定义,如下面的最小示例所示。我试图将常量MYConst的值分配给成员变量myClassInst.MSGTYPE。之后,我想用unittest断言宏检查值,但由于类型不同,检查失败。不同的类型也显示在下面的输出中。

我不明白,为什么类型不同?写这段代码的正确方法是什么?我是Python的新手,所以提前感谢您对的支持

from ctypes import *
import unittest
MyType  = c_ubyte
MYConst = MyType(0xED)
class MyClass (Structure):
_fields_ = [ ("MSGTYPE", MyType) ]
class myTest(unittest.TestCase):
def test(self):
myClassInst = MyClass()
myClassInst.MSGTYPE = MYConst
print(type(MYConst))
print(type(myClassInst.MSGTYPE))
self.assertEqual(MYConst, myClassInst.MSGTYPE)
if __name__ == '__main__':
unittest.main()

输出为:

<class 'ctypes.c_ubyte'>
<class 'int'>
F
======================================================================
FAIL: test (__main__.myTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mimimumexample.py", line 16, in test
self.assertEqual(MYConst, myClassInst.MSGTYPE)
AssertionError: c_ubyte(237) != 237
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)

在ctypes结构中,ctypes"有益的";在读取/写入成员变量时转换为Python对象,因此读取MYConst会生成Python int。

MYConst = MyType(0xED)更改为MyConst = 0xED,它将正常工作。

(感谢您提供一个带有单元测试的独立示例!(

最新更新