在Python中存储对引用的引用?

pro*_*ble 6 python reference

使用Python,有没有办法存储对引用的引用,以便我可以在另一个上下文中更改引用引用的内容?例如,假设我有以下类:

class Foo:
   def __init__(self):
      self.standalone = 3
      self.lst = [4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

我想创建类似于以下内容的东西:

class Reassigner:
   def __init__(self, target):
      self.target = target
   def reassign(self, value):
      # not sure what to do here, but reassigns the reference given by target to value
Run Code Online (Sandbox Code Playgroud)

如下代码

f = Foo()
rStandalone = Reassigner(f.standalone) # presumably this syntax might change
rIndex = Reassigner(f.lst[1])
rStandalone.reassign(7)
rIndex.reassign(9)
Run Code Online (Sandbox Code Playgroud)

会导致f.standalone等于7f.lst等于[4, 9, 6].

从本质上讲,这将是指向指针的类似物.

小智 6

简而言之,这是不可能的.完全没有.最接近的等价物是存储对要重新分配其成员/项目的对象的引用,加上属性名称/索引/键,然后使用setattr/ setitem.但是,这会产生完全不同的语法,您必须区分这两者:

class AttributeReassigner:
    def __init__(self, obj, attr):
        # use your imagination
    def reassign(self, val):
        setattr(self.obj, self.attr, val)

class ItemReassigner:
    def __init__(self, obj, key):
        # use your imagination
    def reassign(self, val):
        self.obj[self.key] = val

f = Foo()
rStandalone = AttributeReassigner(f, 'standalone')
rIndex = ItemReassigner(f.lst, 1)
rStandalone.reassign(7)
rIndex.reassign(9)
Run Code Online (Sandbox Code Playgroud)

我实际上使用了非常相似的东西,但有效的用例很少.对于全局/模块成员,您可以使用模块对象,也可以使用模块对象globals(),具体取决于您是在模块内部还是在模块外部.根本没有局部变量的等价物 - 结果locals()不能用于可靠地改变当地人,它只对检查有用.

我实际上使用了非常相似的东西,但有效的用例很少.