Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python bytearray引用与值类型?_Python_Arrays_Pass By Reference - Fatal编程技术网

Python bytearray引用与值类型?

Python bytearray引用与值类型?,python,arrays,pass-by-reference,Python,Arrays,Pass By Reference,在Python中,当bytearray传递给函数时,它是通过引用还是通过值传递的 在Python3.7中,我试图模拟HTTPResponse对象进行测试。当我从http.client.HTTPResponse对象内部复制代码时,得到的结果与标准库不同 我的代码: #I call the mock buffer like this intBytesBuffered = self.HTTPResponseMock.readinto(tempBuffer) HTTPResponseMock def

在Python中,当bytearray传递给函数时,它是通过引用还是通过值传递的

在Python3.7中,我试图模拟HTTPResponse对象进行测试。当我从http.client.HTTPResponse对象内部复制代码时,得到的结果与标准库不同

我的代码:

#I call the mock buffer like this
intBytesBuffered = self.HTTPResponseMock.readinto(tempBuffer)
HTTPResponseMock

def read(self, amt = None):

    if amt is not None:
        # Amount is given, implement using readinto
        b = bytearray(amt)
    else:
        b = bytearray(len(self.MockedContentBuffer))

    n = self.readinto(b)
    return memoryview(b)[:n].tobytes()

def readinto(self, b):
    """docstring"""

    #mvb = memoryview(b)
    bufferSize = len(b)
    contentSize = len(self.MockedContentBuffer)
    b.clear()
    if bufferSize >= contentSize:
        b = self.MockedContentBuffer
    else:
        b = self.MockedContentBuffer[0:bufferSize]
        del self.MockedContentBuffer[0:bufferSize]

    return len(b)
http.client.HTTPResponse中的相关函数可在第436-500行找到

标准库中最重要的摘录如下,其中read调用readinto:

b = bytearray(amt)
n = self.readinto(b)
return memoryview(b)[:n].tobytes()

标准库在调用缓冲区时做的事情与我差不多,但当它运行时,摘录中的byteArray
b
返回,其中包含数据。当我调用read时,
tempBuffer
返回空?

在显示的代码中,
read
从未被调用,并且
limitBuffer
不会出现。问题在于
readinto
b
包含一个引用,当新值被分配给
b
时,该引用会被覆盖。新引用不会在
readinto
末尾返回或以其他方式分发。Python只会将堆引用放在堆栈上。你不能像在C中那样按值传递数组。@gilch:你可以在C中按值传递数组吗?这对我来说是个新闻。。。非常确定您根本无法传递数组(因为它们只是降级为指向数组的指针)。我会注意到Python的不可变类型的行为就像是通过值传递一样,这通常足够接近。@ShadowRanger数组可以在C中的堆栈上生存(而不仅仅是堆)。要按值传递它,只需将其包装在结构中。