Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transitive value assignation in Python classes

I don't think it can be done easily, but here is the thing:

Assume you have a simple class like this:

class Demo:
    a = 'to update'
    b = a

As you can see, I want the variable 'b' to be another name for variable 'a'. So, what I want to do is something like this:

>>> demo = Demo()
>>> demo.a
'to update'
>>> demo.b
'to update'
>>> demo.b = 'updated'
>>> demo.b
'updated'
>>> demo.a
'updated'

So, this is an example of what I want to achieve. What I want to do is to set a value to variable 'a' when I set a value for variable 'b'. My first guess is to set both variable to have a reference to the actual value, so they're pointing to the same element.

Any guess? Previous thanks to any one answering!

PD: The value must be a string.

like image 474
FernandoEscher Avatar asked Sep 29 '26 23:09

FernandoEscher


1 Answers

You can't hook into assignment to get the effect you're looking for. You're right that you'll need to set both a and b to the same mutable object, and change your assignment to be something that mutates the object.

class Demo:
    a = ['to update']
    b = a

>>> demo = Demo()
>>> demo.a[0]
'to update'
>>> demo.b[0]
'to update'
>>> demo.b[0] = 'updated'
>>> demo.b[0]
'updated'
>>> demo.a[0]
'updated'

You could also use properties to achieve the same effect, though a and b would be instance attributes, not class attributes:

class Demo(object):
    def __init__(self):
        self._shared = None

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

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

    @property
    def b(self):
        return self._shared

    @b.setter
    def b(self, value):
        self._shared = value
like image 52
Ned Batchelder Avatar answered Oct 02 '26 13:10

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!