如何在Python中为变量分配内存地址? [英] How to assign a memory address to a variable in Python?
问题描述
这是场景:
我愚蠢地忘记了将返回的对象分配给一个变量:
I foolishly forget to assign the returned object to a variable:
>>> open("random_file.txt")
<open file 'random_file.txt', mode 'r' at 0x158f780>
是否可以将内存地址直接分配给变量?大致等同于
Is there a way to directly assign the memory address to a variable? Something roughly equivalent to
int *ptr;
*ptr = 0x158f780;
计数点:
-
在这种情况下,我可以丢弃该对象-在读取模式下打开文件,并且该对象将由GC收集.但是我对需要确定性地释放资源的方案感兴趣.
In this case I can just discard the object - the file's opened in read mode and the object will be collected by the GC. But I'm interested in a solution for the scenario where I need to free the resource in a deterministic way.
我假设"at 0x158f780"部分只是对象的id()-恰好是CPython中的内存地址(这是实现特定的,可能会更改,等等") .因此,我对这两种情况都感兴趣-将变量绑定到id()值会很好(更便于移植,而不会),但是将其绑定到裸内存地址也可以.
I assume that the "at 0x158f780" part is just the id() of the object - which happens to be the memory address in CPython ("this is implementation-specific and may change, blah-blah"). So I'm interested in both scenarios - binding a variable to the id() value would be great (more portable and what not), but binding it to a bare memory address would also be O.K.
我在google上搜索了一些与"python指针"相关的变量/内存地址分配及类似内容,但是我的google-fu似乎不够强大.
I did google around a bit for anything "python pointer"-related, variable/memory address assignment and similar, but it seems my google-fu is not strong enough.
干杯
阅读答案并浏览python文档后,一些切线:REPL _ var引用了文件对象.一旦将_分配给下一个命令的结果,我就假定其refcount变为0.文件对象将从内存中删除,并且如果我们假设它实现了合理的__del__
方法,则它应该处理所有低级详细信息,即关闭文件等. http://docs.python.org/reference/datamodel.html#object.__del__ 详细介绍一般情况.
Some tangents after reading the answers and browsing the python docs: the file object is referenced by the REPL _ var. As soon as _ is assigned to the result of the next command, I assume its refcount goes to 0. The file object is removed from memory, and if we assume it implements a sane __del__
method, it should take care of all the low-level details, i.e. closing the file and so on. http://docs.python.org/reference/datamodel.html#object.__del__ details the general scenario.
那我将把0.0.0.0 stackoverflow.com添加到/etc/hosts ...
That and I'll be adding 0.0.0.0 stackoverflow.com to /etc/hosts...
推荐答案
Python是高级语言.您不能(无论如何也不直接)弄乱内存地址,因此答案是否定的.
Python is a high level language. You can't (not directly anyway) mess with memory addresses so the answer is no.
然而,REPL确实方便地将最后一个表达式的结果存储在魔术变量_
中.您可以从那里获取.引用您的示例.
The REPL however does conveniently store the result of the last expression in a magic variable _
. You can fetch it from there. To quote your example.
>>> open("/etc/passwd","r") #Oops I forgot to assign it
<open file '/etc/passwd', mode 'r' at 0x7f12c58fbdb0>
>>> f = _ # Not to worry. It's stored as _
>>> f
<open file '/etc/passwd', mode 'r' at 0x7f12c58fbdb0>
>>>
这篇关于如何在Python中为变量分配内存地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!