Get An Object From Its Address
Solution 1:
id
is only defined as a number *unique to the element among currently existing elements. Some Python implementations (in fact, all main ones but CPython) do not return the memory address.
%~> pypy
Python 2.7.3 (480845e6b1dd219d0944e30f62b01da378437c6c, Aug 08 2013, 17:02:19)
[PyPy 2.1.0with GCC 4.8.120130725 (prerelease)] on linux2
Type"help", "copyright", "credits"or"license"for more information.
And now for something completely different: ``arguably, everything is a niche''
>>>> a = 1
>>>> b = 2
>>>> c = 3
>>>> id(a)
9L
>>>> id(b)
17L
>>>> id(c)
25L
So you have to guarantee that it is the memory address. Furthermore, because of this Python provides no id → object
mapping, especially as the object that an id
maps to can be changed if the original is deleted.
You have to ask why you're holding the id
. If it's for space reasons, bear in mind that containers actually hold references to items, so [a, a, a, a, a]
actually takes less space than [id(a), id(a), id(a), id(a), id(a)]; a
.
You can consider also making a dict
of {id: val}
for all the relevant items and storing that. This will keep val
alive, so you can use weakref
s to allow the val
s to be garbage collected. Remember, use weakref
if you want a weakref
.
Solution 2:
My actual problem is " I have a python module in which a class had been defined "Class Myclass". I am reusing the module in my new code. I want the object of Myclass which is defined in the old module have to be accessed in my new file. Can any one suggest me a way to achieve this. I don't have right to access the module where the class has defined. I can mange to get the class name with garbage collector.
If you are reusing the module, then you have access to that module.
For example if said module creates the object like this:
classMyClass:
pass
myobj = MyClass()
Then you can import that reference too when you import the module:
from othermodule importMyClass, myobj
Solution 3:
By the id
you can't. By name:
classA:
def__init__(self,val):
self.v = val
myInst = A(3)
printeval("myInst").v
>>> 3
Post a Comment for "Get An Object From Its Address"