Aderam
Aderam

Reputation: 65

simulating pointer like behavior for python class attribute

I am trying to simulate a pointer-like behavior for a python3 class attribute. In the following example I would like to have obj.b pointing to obj.a, such that if obj.a value changes at runtime obj.b value will change to.

   # not working as expected
   class A:
      def __init__(self, value):
         self.a = value
         self.b = getattr(self, 'a')
   obj = A('banana')
   # now changing my mind
   obj.a = 'apple'
   # I would like to have obj.b == 'apple', not 'banana' 

I imagine that I am trying to do a dirty trick that should be better avoided, but for my specific task it would be pretty helpful

Upvotes: 1

Views: 157

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11942

You could just set obj.b as a property:

class A:
    def __init__(self, value):
        self.a = value

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

    obj = A('banana')
    # now changing my mind
    obj.a = 'apple'
    print(obj.b) # apple

Of course there's a little more to properties than that. For example if you try to do something like this:

obj.b = 'orange'

It will fail because you can't set that property. But this

obj.a = 'orange'

Would always work, and this test would always be True:

obj.a == obj.b

A working example in the console:

>>> class A:
...     def __init__(self, value):
...             self.a = value
...     @property
...     def b(self):
...             return self.a
...
>>> a = A('apple')
>>> a.a
'apple'
>>> a.b
'apple'
>>> a.a = 'orange'
>>> a.b
'orange'
>>> a.b = 'hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Upvotes: 4

Related Questions