在python中通过其ID更新变量 [英] Updating a variable by its id within python

查看:153
本文介绍了在python中通过其ID更新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何通过Python中的id获得变量的值,例如:

I know how to get the value of a variable by its id in Python like:

a = "hello world!"
ctypes.cast(id(a), ctypes.py_object).value

我不知道

最简单的方法是:

ctypes.cast(id(a), ctypes.py_object).value = "new value"

不起作用。

推荐答案

为什么不起作用



对象 ctypes.cast(id(a),ctypes.py_object)仅提供内存中对象的视图。因此,在更新 value 属性时,您无需更新对象本身,而要做的就是创建一个新对象,并使 value

Why it did not work

The object ctypes.cast(id(a), ctypes.py_object) only provides a view on an object in memory. So when updating the value attribute you do not update the object itself, all you do is create a new object and make value point to it.

import ctypes

a = "Hello World!"
py_obj = ctypes.cast(id(a), ctypes.py_object)

id(py_obj.value) # 1868526529136

py_obj.value = 'Bye Bye World!'

# Here we can see that `value` now points to a new object
id(py_obj.value) # 1868528280112



如何突变任何对象



ctypes ,以直接更新内存,从而突变任何对象。

How to mutate any object

It is possible, with ctypes, to update memory directly and thus to mutate any object. That is even true for strings which are said to be immutable.

下面的内容作为练习很有趣,但是永远不要使用情况。

The following is interesting as an exercice, but should never be used in other circumstances. Among other things it can corrupt object reference count, leading to memory management errors.

import ctypes
import sys

def mutate(obj, new_obj):
    if sys.getsizeof(obj) != sys.getsizeof(new_obj):
        raise ValueError('objects must have same size')

    mem = (ctypes.c_byte * sys.getsizeof(obj)).from_address(id(obj))
    new_mem = (ctypes.c_byte * sys.getsizeof(new_obj)).from_address(id(new_obj))

    for i in range(len(mem)):
        mem[i] = new_mem[i]

以下是示例。在这些之中,您将找到为什么除非您真的知道自己在做什么或作为锻炼,否则不得使用以上代码的原因。

Here are examples. Among these you will find reasons why you must not use the above code unless you really know what you are doing or as an exercice.

s = 'Hello World!'
mutate(s, 'Bye World!!!')
print(s) # prints: 'Bye World!!!'

# The following happen because of Python interning
mutate('a', 'b')
print('a') # prints: 'b'

mutate(1, 2)
print(1) # prints: 2

尤其是上面的示例根据版本和环境,使Python退出时出现未知错误代码或崩溃。

In particular, the above example makes Python exit with an unknown error code or crash, depending on the version and environment.

这篇关于在python中通过其ID更新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆