python3 指针_在Python中模拟指针

几乎就像我投票赞成的短暂 答案一样,您可以使用Python的内置属性函数。它将执行与refephemient答案中的类几乎类似的操作,只是现在,您不必调用被迫使用get和set方法来访问ref实例的方法,而只需调用已在类定义中作为属性分配的实例的属性。从Python文档(除非我将C更改为ptr):

class ptr(object):

def __init__(self):

self._x = None

def getx(self):

return self._x

def setx(self, value):

self._x = value

def delx(self):

del self._x

x = property(getx, setx, delx, "I'm the 'x' property.")

两种方法都像C指针一样工作,而无需诉诸global。例如,如果您有一个使用指针的函数:

def do_stuff_with_pointer(pointer, property, value):

setattr(pointer, property, value)

例如

a_ref = ptr() # make pointer

a_ref.x = [1, 2] # a_ref pointer has an array [1, 2]

b_ref = a_ref # b_ref points to a_ref

# pass ``ptr`` instance to function that changes its content

do_stuff_with_pointer(b_ref, 'x', 3)

print a_ref.x # outputs 3

print b_ref.x # outputs 3

另一个非常疯狂的选择是使用Python的ctypes。尝试这个:

from ctypes import *

a = py_object([1,2]) # a has an array

b = a # b points to a

b.value = 2 # derefernce b to store 2 in a

print a.value # outputs 2

print b.value # outputs 2

或者如果您想真正看上

from ctypes import *

a = py_object([1,2]) # a has an array

b = pointer(a) # b points to a

b.contents.value = 2 # derefernce b to store 2 in a

print a.value # outputs 2

print b.contents.value # outputs 2

这更像是OP的原始请求。疯!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值