问题
alist += [4]
and alist = alist + [4]
are different as the first changes the reference of alist whereas the latter doesn't. I tried this below on IDLE by using id()
and it seems like it is correct claim.
Code executed on IDLE (Python 3.6.1)
>>> alist = [1, 2, 3]
>>> id(alist)
50683952
>>> alist += [4]
>>> id(alist)
50683952
>>> alist = alist + [4]
>>> id(alist)
50533080
Here is documentation for id()
: https://docs.python.org/3/library/functions.html#id
Is it possible to get reference to memory address programatically, identify whether the location has a list or a dictionary, read the contents and update the content using reference?
NOTE:
I found 2 relevant stackoverflow posts but I am not sure if they answer my question.
- print memory address of Python variable
- Accessing object memory address
回答1:
You are trying to do something like in C, with a Dereference operator, such as * , you can read more about it in this question. I'm sure that Python has no support for doing what you are trying to achieve, you have to change your mind paradigm, think different to get the results you want.
As you read, you can "get the memory address" from an object, but you want ever find a way (at least in python 2 - 3) to get the way back
回答2:
If you need to check if a Python object is a dict or list, use isinstance
. If you need to check if the unique identifier for an object (related to memory address, I believe), use id
. If you need to check equality by value, use ==
.
There is no reason to do what you are doing right now: everything in Python is a reference-counted, garbage-collected pointer, you should not worry about how this is implemented. In addition to being prone to break version to version, it also is intentionally not exported in the Python API.
If you need the address of a PyObject
in the C API, well it's already a pointer (and already done for you). You can use the C API to check if a pointer that is known to be a PyObject is a dict
or list
accordingly.
来源:https://stackoverflow.com/questions/45449764/get-memory-address-in-python-identify-if-it-is-list-or-a-dictionary-and-update