Get the App
SLTechnology News&Howtos  ›  Development  › 

How does Python get the value of a variable through the variable ID

Shulou Source: shulou.com Published: 2022-05-31 17:09:42 11月03日 Update

This article introduces the relevant knowledge of "how Python gets the value of variables through variable ID". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Get the value of the variable through the variable ID

It is known that the id that gets the variable uses the function id (), so what is its inverse function?

The answer is: PyObj_FromPtr, accordingly, write a function di (), which can get the value of the variable according to the result of id ().

From _ ctypes import PyObj_FromPtr def di (obj_id): "" get the value of the variable through the variable ID "" return PyObj_FromPtr (obj_id) if _ name__ = "_ _ main__": I = {"j": 99, "name": "jack"} var_id = id (I) print (var_id) print (di (var_id))

What's the point of doing this?

The answer is that Python script interpretation is useful. If you want to write a Python script interpreter, you get a line of string: "I = j". Normally you split the string to get I = "j", but if you already know JF10, how do you make I = 10? After a series of id () di () Dafa, this small goal can be achieved.

The method code for the second implementation is similar

Import ctypes value='hello world' # defines a string variable address=id (value) # gets the address of the value and assigns it to addressget_value=ctypes.cast (address, ctypes.py_object). Value # read the variable print (get_value) in the address how to view the id of a variable

If there are any mistakes, please correct them.

Use the id () function

This is the end of the content of "how Python gets the value of a variable through the variable ID". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Variables functions characters strings content addresses situations more knowledge answers scripts interpretation practicality achievement next one line code inverse function dilemma Dafa Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Shulou Information NVidia macOS MySQL