Are python variables pointers? or else what are they?

前端 未结 9 1920
借酒劲吻你
借酒劲吻你 2020-11-22 07:01

Variables in Python are just pointers, as far as I know.

Based on this rule, I can assume that the result for this code snippet:

i = 5
j = i
j = 3          


        
9条回答
  •  灰色年华
    2020-11-22 07:44

    In Python, everything is object including the memory pieces themselves that you are returned. That means, when new memory chunk is created (irrespective of what've you created: int, str, custom object etc.), you have a new memory object. In your case this is the assignment to 3 which creates a new (memory) object and thus has a new address.

    If you run the following, you see what I mean easily.

    i = 5
    j = i
    print("id of j: {}", id(j))
    j = 3
    print("id of j: {}", id(j))
    

    IMO, memory wise, this is the key understanding/difference between C and Python. In C/C++, you're returned a memory pointer (if you use pointer syntax of course) instead of a memory object which gives you more flexibility in terms of changing the referred address.

提交回复
热议问题