What happens when you assign the value of one variable to another variable in Python?

后端 未结 10 769
太阳男子
太阳男子 2020-11-30 00:54

This is my second day of learning python (I know the basics of C++ and some OOP.), and I have some slight confusion regarding variables in python.

Here is how I unde

相关标签:
10条回答
  • 2020-11-30 01:40

    As @DeepSpace mentioned in the comments, Ned Batchelder does a great job demystifying variables (names) and assignments to values in a blog, from which he delivered a talk at PyCon 2015, Facts and Myths about Python names and values. It can be insightful for Pythonistas at any level of mastery.

    0 讨论(0)
  • 2020-11-30 01:44

    As a C++ developer you can think of Python variables as pointers.

    Thus when you write spam = 100, this means that you "assign the pointer", which was previously pointing to the object 42, to point to the object 100.

    Earlier on, cheese was assigned to point to the same object as spam pointed to, which happened to be 42 at that time. Since you have not modified cheese, it still points to 42.

    Immutability has nothing to do with it in this case, since pointer assignment does not change anything about the object being pointed to.

    0 讨论(0)
  • 2020-11-30 01:44

    When you run spam = 100 python create one more object in the memory but not change existing. so you still have pointer cheese to 42 and spam to 100

    0 讨论(0)
  • 2020-11-30 01:45

    numpy.copy() function page has an explanation

    https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.html

    The example it gives is as follows:

    Create an array x, with a reference y and a copy z:

    x = np.array([1, 2, 3])
    y = x
    z = np.copy(x)
    

    Note that, when we modify x, y changes, but not z:

    x[0] = 10
    x[0] == y[0]
    True
    x[0] == z[0]
    False
    
    0 讨论(0)
提交回复
热议问题