几乎就像我投票赞成的短暂 答案一样,您可以使用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的原始请求。疯!