我想实现一个继承自RawIOBase的类。我正在努力实现readinto方法。基本上,我不知道如何更改作为参数传递的bytearray对象的内容。
我尝试过以下(天真的)方法:
def readinto(self, b):
data = self.read(len(b))
b = data
return len(data)
但是,正如我怀疑的那样,这会将新bytearray
对象分配给局部变量b并且它不会更改原始bytearray
.
我想实现一个继承自RawIOBase的类。我正在努力实现readinto方法。基本上,我不知道如何更改作为参数传递的bytearray对象的内容。
我尝试过以下(天真的)方法:
def readinto(self, b):
data = self.read(len(b))
b = data
return len(data)
但是,正如我怀疑的那样,这会将新bytearray
对象分配给局部变量b并且它不会更改原始bytearray
.
来自以下文档RawIOBase.readinto
:
将字节读入预先分配的、可写的类似字节的对象 b中,并返回读取的字节数。如果对象处于非阻塞模式并且没有可用的字节,则返回 None。
它有点令人困惑,但您需要写入类似字节的对象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)
看看 CPython 的实现BytesIO.readinto
。基本上它是从对象的缓冲区到函数输入缓冲区的 memcpy。