Is a variable the name, the value, or the memory location?

前端 未结 4 760
遥遥无期
遥遥无期 2020-11-30 11:39

I\'ve been learning Python for a few months, and also know very little C, and I was wondering if anyone could clear this doubt up for me:

Is a variable the name, the

4条回答
  •  醉梦人生
    2020-11-30 12:35

    In Python variables are best considered as names.

    In the case of numbers, numbers are immutable so reassigning a variable will always make the variable point to a different number without changing the number.

    x = 1
    y = x
    x += 1 # y is still 1
    

    The difference is clearer with mutable objects, where you can change a value OR make the variable refer to a different value

    x = [1,2,3]
    y = x
    x.append(4) # I mutated x's value, so y is now [1,2,3,4]
    x = [] # I made x point to a different list, so y is still [1,2,3,4]
    

    Recommended reading:

    http://web.archive.org/web/20180411011411/http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

    http://me.veekun.com/blog/2012/05/23/python-faq-passing/

提交回复
热议问题