【问题标题】:Python buffer(long(-10)): "TypeError: buffer object expected"Python 缓冲区(长(-10)):“类型错误:预期缓冲区对象”
【发布时间】:2013-11-08 22:08:24
【问题描述】:

我一直在尝试探索 python 如何在我的系统上存储 longs 符号。

不确定是不是这样,我已经尝试过buffer(long(-10)),希望它能拉近我的距离。

但我有TypeError: buffer object expected

来自help(buffer)

class buffer(object)
 |  buffer(object [, offset[, size]])
 |
 |  Create a new buffer object which references the given object.
 |  The buffer will reference a slice of the target object from the
 |  start of the object (or at the specified offset). The slice will
 |  extend to the end of the target object (or with the specified size).

我认为一切都是 python 中的对象,我解释了这个文档字符串,以便我可以将任何对象提供给缓冲区的 init。好像不是这样的。

你能帮我理解发生了什么吗?

【问题讨论】:

  • “我一直在尝试探索 python 如何在我的系统上存储 longs 的符号。”然后只需下载源代码并阅读Include/longintrepr.h。引用:Negative numbers are represented with ob_size < 0; zero is represented by ob_size == 0. 要了解 ob_size 是什么,您应该阅读 Python C/API 的 PyObject_VAR_HEAD 宏。

标签: python buffer typeerror


【解决方案1】:

buffer() function适用于支持缓冲区协议的对象:

object 参数必须是支持缓冲区调用接口的对象(如字符串、数组和缓冲区)。

请注意,该功能实际上已被弃用;它已在很大程度上被memoryview() 取代,返回memoryview type。但是,这仍然不会让您深入了解 Python 长整数的内部结构,因为该函数仅适用于仍然支持缓冲区协议的对象。

Python 3 文档在C API documentation 中包含有关缓冲区协议的更多信息:

Python 中可用的某些对象封装了对底层内存数组或缓冲区的访问。

[...]

虽然这些类型中的每一种都有自己的语义,但它们都有一个共同的特点,即由可能很大的内存缓冲区支持。然后,在某些情况下,最好直接访问该缓冲区而不需要中间复制。

因此,这些函数旨在提高访问更大数据块的效率,而不是让您深入了解底层 C 结构。

【讨论】:

    猜你喜欢
    • 2012-05-30
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 2020-07-13
    相关资源
    最近更新 更多