Equivalent to Python pointers

In python, everything works by reference:

>>> a = 1
>>> d = {'a':a}
>>> d['a']
1
>>> a = 2
>>> d['a']
1

I need something like this

>>> a = 1
>>> d = {'a':magical pointer to a}
>>> d['a']
1
>>> a = 2
>>> d['a']
2

What would you replace the magic pointer with so that python returns what I want.

I would appreciate general solutions (not only for the above dictionary with independent variables, but also for other collections and class / instance variables)

+4
source share
5 answers

What about a mutable data structure?

>>> a = mutable_structure(1)
>>> d = {'a':a}
>>> d['a']
1
>>> a.setValue(2)
>>> d['a']
2

The implementation may look like

class mutable_structure:
  def __init__(self, val):
    self.val = val

  def __repr__(self):
    return self.val
+4
source

The standard solution is to simply use a list; this is the simplest mutable structure.

a = [1]
d = {'a': a}
a[0] = 2
print d['a'][0]
+2
source

, 1 python, .. .

, ,

class Mutable(object):
    pass

a = Mutable()
a.value = 1

d = {'a':a}
a.value = 3

d['a'].value 3 .

, .., , , , , .

+1

, - :

class DRefsA(object):
    a = 4

    @property
    def d(self):
        return self.a

    @d.setter
    def d(self, value):
        self.a = value
0

, , lamda

a = 1
d = {'a': lambda  : a}
print(d['a']()) #output 1
a = 2
print(d['a']()) #output 2
0

Source: https://habr.com/ru/post/1728476/


All Articles