gpt4 book ai didi

python - 如何实现 readinto() 方法

转载 作者:太空狗 更新时间:2023-10-30 01:11:58 30 4
gpt4 key购买 nike

我想实现一个继承自 RawIOBase 的类.我正在努力实现 readinto 方法。基本上,我不知道如何更改 bytearray 的内容作为参数传递的对象。

我试过以下(天真的)方法:

def readinto(self, b):
data = self.read(len(b))
b = data
return len(data)

但是,正如我怀疑的那样,这会将新的 bytearray 对象分配给局部变量 b 并且它不会更改原始 bytearray 的内容.

最佳答案

来自 RawIOBase.readinto 的文档:

Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. If the object is in non-blocking mode and no bytes are available, None is returned.

它有点困惑,但你需要写入 bytes-like对象 b(未读取)

示例用法

import io

class MyIO(io.RawIOBase):
def readinto(self, b):
msg = b'hello'
b[:len(msg)] = msg
return len(msg)

i = MyIO()
buf = bytearray()
i.readinto(buf)
print(buf)

看一下 BytesIO.readinto 的 CPython 实现.基本上它会从对象的缓冲区到函数输入缓冲区。

关于python - 如何实现 readinto() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45805111/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com