Why the id(string) does not return the address of string
import ctypes
a = '开发者_开发技巧abc'
b = ctypes.string_at(id(a), 3)
c = ctypes.string_at(id(a) + 20, 3)
I expect the result of b to be 'abc', but it is not; and the result of c is 'abc'. I don't know why. Anyone can explain me?
In Python, a str
is an object, so there is no guarantee about what it looks like in memory. Probably, it contains some more information, like the length of the string. In your case, the size of this "metadata" is apparently 20 bytes.
Possibly, the object itself does not even contain the actual string, but rather a pointer to it. If that is the case, in your situation the actual string happens to be located 20 bytes after the object.
Either way, this is an implementation detail. None of this behaviour should be relied upon in any serious code.
精彩评论