1
我想這是最好的代碼和註釋說明:通過擴展創建緩衝區類的Python海峽
import struct
class binary_buffer(str):
def __init__(self, msg=""):
self = msg
def write_ubyte(self, ubyte):
self += struct.pack("=B", ubyte)
return len(self)
Output
>> bb = binary_buffer()
>> bb # Buffer starts out empty, as it should
''
>> bb.write_ubyte(200)
1 # We can see that we've successfully written one byte to the buffer
>> bb
'' # Huh? We just wrote something, but where has it gone?
我會說,在一般情況下,分配給「自我」是錯誤的。至少我不能拿出這個合法的用途。 –
@doomster:爲什麼呢?你會怎麼做呢? – Peter
@TahitiPetey因爲你只是將自己綁定到名字self,這通常是你當前的對象。要更改當前對象,請分配給* its *屬性之一,或等效地調用其中一個方法。 – phihag