Domanda

C'è un tipo buffer in python, ma non so come posso usarlo.

Python doc la descrizione è:

  

buffer(object[, offset[, size]])

     

L'argomento oggetto deve essere un oggetto che supporta l'interfaccia chiamata tampone (come le stringhe, array e buffer). Un nuovo oggetto del buffer verrà creato che fa riferimento l'argomento oggetto. L'oggetto tampone sarà una fetta dall'inizio di oggetto (o dalla offset specificato). La fetta si estenderà fino alla fine di oggetto (o avrà una lunghezza in argomento size).

È stato utile?

Soluzione

Un esempio d'uso:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

Il buffer in questo caso è un sub-stringa, a partire dalla posizione 6 con lunghezza 5, e non ci vuole spazio extra -. Fa riferimento a una fetta della stringa

Questa non è molto utile per le stringhe brevi come questo, ma può essere necessario quando si utilizza grandi quantità di dati. Questo esempio utilizza un bytearray mutabile:

>>> 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'

Questo può essere molto utile se si vuole avere più di una vista sui dati e non si vuole (o non può) contenere più copie in memoria.

Si noti che buffer è stato sostituito dal più chiamato memoryview in Python 3, anche se è possibile utilizzare sia in Python 2.7.

Si noti inoltre che non è possibile implementare un'interfaccia buffer per i propri oggetti senza approfondire l'API C, vale a dire non si può farlo in puro Python.

Altri suggerimenti

Credo buffer sono per esempio utile quando ci si interfaccia Python per librerie native. (Guido van Rossum spiega buffer in questa mailinglist messaggio ).

Per esempio, NumPy sembra uso dei buffer per la memorizzazione di dati efficiente:

import numpy
a = numpy.ndarray(1000000)

la a.data è una:

<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top