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

后端 未结 10 812
太阳男子
太阳男子 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:25

    Python is neither pass-by-reference or pass-by-value. Python variables are not pointers, they are not references, they are not values. Python variables are names.

    Think of it as "pass-by-alias" if you need the same phrase type, or possibly "pass-by-object", because you can mutate the same object from any variable that indicates it, if it's mutable, but reassignment of a variable (alias) only changes that one variable.

    If it helps: C variables are boxes that you write values into. Python names are tags that you put on values.

    A Python variable's name is a key in the global (or local) namespace, which is effectively a dictionary. The underlying value is some object in memory. Assignment gives a name to that object. Assignment of one variable to another variable means both variables are names for the same object. Re-assignment of one variable changes what object is named by that variable without changing the other variable. You've moved the tag but not changed the previous object or any other tags on it.

    In the underlying C code of the CPython implementation, every Python object is a PyObject*, so you can think of it as working like C if you only ever had pointers to data (no pointers-to-pointers, no directly-passed values).

    you could say that Python is pass-by-value, where the values are pointers… or you could say Python is pass-by-reference, where the references are copies.

提交回复
热议问题