有点迷糊,headers_set[:] = [status, response_headers]

2013-08-27 14:58:46 +08:00
 hustlzp
今天在看关于WSGI的PEP333文档:

http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side

看到一行代码有点迷糊:

headers_set[:] = [status, response_headers]

我只知道list[:]的作用在于拷贝一个新的列表对象,一般用于防止2个变量引用到了一个对象,这样的话改变一方会影响到另一方的值,比如:

L = [1, 2]
def changer(L):
L[0] = 2

changer(L) # L = [2, 2]
changer(L[:]) # L = [1, 2]

但是 headers_set[:] = [status, response_headers] 却有点看不懂了。右边是一个新的对象,左边也是一个拷贝的新的对象,把一个对象给另一个对象赋值有意义吗?

求大家指点!
2896 次点击
所在节点    Python
6 条回复
SErHo
2013-08-27 15:22:11 +08:00
headers_set[:] 是这个函数外定义的,这个就是给 headers_set 赋值啊,举个例子如下:

def test():
....h = []
....p = []

....def test_t():
........h = [1, 2]
........p[:] = [1, 2]
....test_t()
....print h
....print p
hustlzp
2013-08-27 15:42:12 +08:00
@SErHo 原来是这样...好怪...

在stackoverflow上找到了一个相关的问题,但不是针对list,而是针对不可变的变量:

http://stackoverflow.com/questions/8447947/is-it-possible-to-modify-variable-in-python-that-is-in-outer-but-not-global-sc

python3的nonlocal关键字也可以解决这个“给外层函数中不可变的变量赋值”的问题:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.
SErHo
2013-08-27 15:48:48 +08:00
@hustlzp 其实我对这种作用域地方的问题也不太清楚,不过要搞明白为啥要这样用,写个例子来试试就知道了。
hustlzp
2013-08-27 15:55:46 +08:00
@SErHo 恩,谢谢!
felix021
2013-08-27 16:13:44 +08:00
@hustlzp 去了解一下python是怎么实现slice的,就会豁然开朗了。

关键字: python __getitme__ __setitem__ slice

TRY:

class A(object):

..def __getitem__(self, key):
....print key
....return 0

..def __setitem__(self, key, value):
....print key, value

a = A()
print a[0:1]
a[0:1] = [1]
wynemo
2013-08-27 21:40:12 +08:00
直接在嵌套函数里些headers_set = [status, response_headers] 会认为在嵌套函数里新声明了一个headers_set 作用范围就在嵌套函数里 不改变外层headers_set的值
headers_set[:] 这样是给headers_set赋值 会改变外层的值

具体用locals看

def test():
....a = []
....def test_t():
........print locals()
........a.extend([1,3])
....test_t()
....print a

test()

def test():
....a = []
....def test_t():
........print locals()
........a = [1, 3]
....test_t()
....print a

test()

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/80381

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX