首页 > 解决方案 > 获取 TypeError:“int”类型的对象在使用 struct.pack() 时没有 len(),但仅在类中

问题描述

我得到这个'TypeError:'int'类型的对象没有len()'用于我试图集成到类中的数据转换函数。在类之外它可以正常工作,将其放入类中,或者尝试在类内部访问它,我得到了同样的错误。

我正在编写的程序在两个 rf/lora 节点之间发送 int/float 类型的数据。(这只是一个更大的遥测程序的一部分)我正在使用 struct.pack() 将数据转换为字节数组以便发送它们。代码是使用 Adafruit 硬件(Feather m4 和 lora 分线板)和库在 CircuitPython 中编写的。

任何关于如何解决问题或导致问题的建议将不胜感激!

下面的代码:

class TransmitState(State):

def __init__(self):
    super().__init__()
    self.entered = time.monotonic()
    self.rf = adafruit_rfm9x.RFM9x(spi, cs, reset, radio_freq)
    self.rf.tx_power = 23
    self.rf.enable_crc = True
    self.rf.node = 1
    self.rf.destination = 2
    led.value = True

# converts data to byte array - line error on ba = ...
def pack_data(self, data_to_pack):
    # First encode the number of data items, then the actual items
    ba = struct.pack("!I" + "d" * len(data_to_pack),     #    <--- Line that's causing the error
                len(data_to_pack), *data_to_pack)
    return ba

# sendData sends the converted data to our 2nd node
def sendData(self, data):
# checks to see if data is null
    if data:
        ts = self.pack_data(data)     #     <--- Call to convert fcn
        self.rf.send(ts)   
        

@property
def name(self):
    return 'transmit'

def enter(self, machine):
    State.enter(self, machine)
    self.entered = time.monotonic()
    led.value = True
    print("Entering Transmit")

def exit(self, machine):
    print("Exiting Transmit")
    State.exit(self, machine)

def update(self, machine):
   
    if State.update(self, machine):
        now = time.monotonic()
        if now - self.entered >= 1.0:
            led.value = False
            print("Transmitting...")
            self.sendData(3) #            <-- FCN Call, 3 is arbitrary 
            machine.go_to_state('idle')

注意:未显示导入和引脚分配

标签: pythonclassadafruitlorastruct.pack

解决方案


该错误是因为您试图获取int.

len()属性仅适用于 dict、list、strings、sets 和 tuples 等可迭代类型。

尝试 :

ba = struct.pack("!I" + "d" * len(str(data_to_pack)), len(str(data_to_pack)), *data_to_pack):

这将做的是将数据转换为字符串,然后获取长度。


推荐阅读