在Python中通过变量的id更新变量

问题描述 投票:0回答:2

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

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

我想知道是否可以通过id覆盖变量值?

最简单的方法,这个:

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

不起作用。

python pointers ctypes
2个回答
10
投票

为什么不起作用

对象

ctypes.cast(id(a), ctypes.py_object)
提供内存中对象的视图。视图本身就是一个对象。因此,当更新
value
属性时,您不会更新对象本身,您所做的只是创建一个新对象,并将视图的
value
属性指向它。

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
,可以直接更新内存,从而改变任何对象。对于据说是不可变的字符串来说也是如此。

以下作为练习很有趣,但不应该在其他情况下使用。除此之外,它可能会破坏对象引用计数,从而导致内存管理错误。

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]

以下是示例。其中,您会发现为什么不能使用上述代码的原因,除非您真的知道自己在做什么或作为练习。

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

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

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

特别是,上面的示例会使 Python 退出并出现未知错误代码或崩溃,具体取决于版本和环境。


2
投票

a
是一个字符串,字符串在Python中是不可变的。

文档示例:

>>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(139966785747344)
>>> print(c_s.value)
Hello World
>>> c_s.value = "Hi, there"
>>> print(c_s)              # the memory location has changed
c_wchar_p(139966783348904)
>>> print(c_s.value)
Hi, there
>>> print(s)                # first object is unchanged
Hello, World
>>>
© www.soinside.com 2019 - 2024. All rights reserved.