Storing a reference to a reference in Python? -
using python, there way store reference reference, can change reference refers in context? example, suppose have following class:
class foo: def __init__(self): self.standalone = 3 self.lst = [4, 5, 6]
i create analogous following:
class reassigner: def __init__(self, target): self.target = target def reassign(self, value): # not sure here, reassigns reference given target value
such following code
f = foo() rstandalone = reassigner(f.standalone) # presumably syntax might change rindex = reassigner(f.lst[1]) rstandalone.reassign(7) rindex.reassign(9)
would result in f.standalone
equal 7
, f.lst
equal [4, 9, 6]
.
essentially, analogue pointer-to-pointer.
in short, it's not possible. @ all. closest equivalent storing reference object member/item want reassign, plus attribute name/index/key, , use setattr
/setitem
. however, yields quite different syntax, , have differentiate between two:
class attributereassigner: def __init__(self, obj, attr): # use imagination def reassign(self, val): setattr(self.obj, self.attr, val) class itemreassigner: def __init__(self, obj, key): # use 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)
i've used similar, valid use cases few , far between. globals/module members, can use either module object or globals()
, depending on whether you're inside module or outside of it. there no equivalent local variables @ -- result of locals()
cannot used change locals reliably, it's useful inspecting.
i've used similar, valid use cases few , far between.
Comments
Post a Comment