Python的“指针”
2026-05-01 12:57:59
发布于:浙江
各位,我们知道,Python没有类似与*p的指针,但是下列这些和地址相关:
1.id(obj) 函数:
Python 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a=3
>>> id(a)
8791055275760
>>>
2.is 关键字:
a is b 等价于id(a)==id(b)
Python 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a=3
>>> b=3
>>> a is b
True
>>> c=[1,2,3]
>>> d=[1,2,3]
>>> c is d
False
>>> id(a)
8790493370096
>>> id(b)
8790493370096
>>> id(c)
46730432
>>> id(d)
46750400
>>>
3.真正的指针:ctypes.addressof():
Python 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from ctypes import *
>>> a=c_int(1)
>>> b=c_int(2)
>>> print(addressof(a))
49419016
>>> print(addressof(b))
49418760
>>>
4.通过地址倒推值:
Python 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from ctypes import *
>>> a=c_int(1)
>>> p=addressof(a)
>>> m=c_int.from_address(p)
>>> m.value
1
>>>
5.swap函数:
from ctypes import *
def swap_int(a,b):
addr1=addressof(a)
addr2=addressof(b)
m1=c_int.from_address(addr1)
m2=c_int.from_address(addr2)
m1.value,m2.value=m2.value,m1.value
全部评论 1
这我是真不知道
2026-05-01 来自 广东
0























有帮助,赞一个