【发布时间】:2021-01-22 23:12:50
【问题描述】:
我想将bytearray 类型写入memoryview 类型。我尝试了什么:
my_memory_view = memoryview(b'hello')
new_byte_string = bytearray(b'world')
my_memory_view = new_byte_string
但它返回了:
AttributeError: can't set attribute
我知道可以通过以下方式写入memoryview:
my_memory_view[0] = 12 #Changes first byte
有没有办法将bytearray 的值自动插入memoryview?
编辑:
我犯了一个错误:错误不是AttributeError 出现问题是因为类型改变了,而是在我的包中我使用(@987654321@)
将显示AttributeError。
【问题讨论】:
-
您不能通过不可变对象写入内存视图。
-
您的代码在我运行时运行良好。没有错误,然后
print(my_memory_view)显示:bytearray(b'world')。请提供minimal reproducible example。 -
另外,虽然您的代码错误且不起作用,但它不会产生您声称的错误消息。 (相反,它默默地做一些与你想要的不同的事情——它只是重新分配一个变量而不是写入内存视图。)
-
在
my_memory_view = new_byte_string之后,type(my_memory_view)是<class 'bytearray'>——它不再是memoryview。
标签: python arrays python-3.x memoryview