1
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 |
2
hustlzp OP @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. |
5
felix021 2013-08-27 16:13:44 +08:00 1
@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] |
6
wynemo 2013-08-27 21:40:12 +08:00 1
直接在嵌套函数里些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() |