最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Python:什么时候通过引用传递变量,什么时候通过值传递?

SEO心得admin35浏览0评论
本文介绍了Python:什么时候通过引用传递变量,什么时候通过值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能的重复:Python:如何通过引用传递变量?

我的代码:

locs = [ [1], [2] ] for loc in locs: loc = [] print locs # prints => [ [1], [2] ]

为什么 loc 不是 locs 元素的引用?

Why is loc not reference of elements of locs ?

Python:除非明确复制,否则一切都作为引用传递[这不是真的吗?]

Python : Everything is passed as reference unless explicitly copied [ Is this not True ? ]

请解释..python如何决定引用和复制?

Please explain.. how does python decides referencing and copying ?

更新:

怎么办?

def compute(ob): if isinstance(ob,list): return process_list(ob) if isinstance(ob,dict): return process_dict(ob) for loc in locs: loc = compute(loc) # What to change here to make loc a reference of actual locs iteration ?

  • locs 必须包含最终处理的响应!
  • 我不想使用enumerate,没有它可以吗?
    • locs must contain the final processed response !
    • I don't want to use enumerate, is it possible without it ?
    • 推荐答案

      Python 中的一切都是按值传递和赋值的,就像 Java 中的一切都是按值传递和赋值一样.Python 中的每个值都是一个对象的引用(指针).对象不能是值.赋值总是复制值(它是一个指针);因此,两个这样的指针可以指向同一个对象.对象永远不会被复制,除非你做了一些明确的事情来复制它们.

      Everything in Python is passed and assigned by value, in the same way that everything is passed and assigned by value in Java. Every value in Python is a reference (pointer) to an object. Objects cannot be values. Assignment always copies the value (which is a pointer); two such pointers can thus point to the same object. Objects are never copied unless you're doing something explicit to copy them.

      对于您的情况,循环的每次迭代都会将列表的一个元素分配给变量 loc.然后将其他内容分配给变量 loc.所有这些值都是指针;您正在分配指针;但您不会以任何方式影响任何对象.

      For your case, every iteration of the loop assigns an element of the list into the variable loc. You then assign something else to the variable loc. All these values are pointers; you're assigning pointers; but you do not affect any objects in any way.

发布评论

评论列表(0)

  1. 暂无评论