Python: copy of a variable

后端 未结 5 1256
[愿得一人]
[愿得一人] 2020-12-10 13:33

Is there a way in to make copy of a variable so that when the value changes of variable \'a\' it copies itself to variable \'b\'?

Example

a=\'hello\'         


        
5条回答
  •  不知归路
    2020-12-10 13:55

    You're exploring how Python deals with references. Assignment is simply binding a reference to an object on the right hand side. So, this is somewhat trivial:

    a = 'foo'
    b = a
    print b is a  #True -- They *are the same object*
    

    However, as soon as you do:

    b = 'bar'
    b is a  #False -- they're not longer the same object because you assigned a new object to b
    

    Now this becomes really interesting with objects which are mutable:

    a = [1]
    b = a
    b[0] = 'foo'
    print a  #What?? 'a' changed?
    

    In this case, a changes because b and a are referencing the same object. When we make a change to b (which we can do since it is mutable), that same change is seen at a because they're the same object.

    So, to answer your question, you can't do it directly, but you can do it indirectly if you used a mutable type (like a list) to store the actual data that you're carrying around.


    This is something that is very important to understand when working with Python code, and it's not the way a lot of languages work, so it pays to really think about/research this until you truly understand it.

提交回复
热议问题