What is Python buffer type for?

后端 未结 2 1979
盖世英雄少女心
盖世英雄少女心 2020-11-28 17:59

There is a buffer type in python, but I don\'t know how can I use it.

In the Python doc the description is:

buffer(object[,

2条回答
  •  佛祖请我去吃肉
    2020-11-28 18:44

    An example usage:

    >>> s = 'Hello world'
    >>> t = buffer(s, 6, 5)
    >>> t
    
    >>> print t
    world
    

    The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

    This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

    >>> s = bytearray(1000000)   # a million zeroed bytes
    >>> t = buffer(s, 1)         # slice cuts off the first byte
    >>> s[1] = 5                 # set the second element in s
    >>> t[0]                     # which is now also the first element in t!
    '\x05'
    

    This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

    Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

    Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

提交回复
热议问题