3
我希望能夠寫的ByteArray緩衝區,並通過調用一個方法來清除它,所以我有一個類,看起來像這樣:繼承和擴展Python字節組
import struct
class binary_buffer(bytearray):
def __init__(self, message=""):
self = message
def write_ubyte(self, ubyte):
self += struct.pack("=B", ubyte)
return len(self)
def clear(self):
self = ""
但是,調用清除( )似乎沒有做任何事情。示例輸出應該是這樣的:
>>> bb = binary_buffer('')
>>> bb
bytearray(b'') # As expected, the bytearray is empty
>>> bb.write_ubyte(255)
1 # Great, we just wrote a unsigned byte!
>>> bb
bytearray(b'\xff') # Looking good. We have our unsigned byte in the bytearray.
>>> bb.clear() # Lets start a new life!
>>> bb
bytearray(b'\xff') # Um... I though I just cleared out the trash?
正如你問類似的問題之前,我想清楚地表明,'self'變量不是在一個特殊的變量**蟒蛇**。這只是我們碰巧用於'class instance'的另一個名字。你應該把它看作一個包含你的'instance'的變量,而不是一個特殊的變量。 – Wessie
@Wessie:我對此還是比較陌生,但是我的代碼如上面的問題所示是否遵循你的描述?我認爲是的,對吧? – Peter