Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report