1

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

3
  • You probably just need b to be a property that returns self.a. But I can't really understand what you are actually trying to do here. Commented Nov 22, 2019 at 8:23
  • Why can't you use obj.a itself? what is the use-case? Commented Nov 22, 2019 at 8:29
  • In short, I am merging several methods which have different variable name definitions, although they are concretely the same stuff. It would be helpful to have only one "driving" variable which will set values to all it's different instances , rather then rescripting all the methods. I am not used to decorators, how would you assign b to be a proprety ? Commented Nov 22, 2019 at 8:30

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

hmm, interesting.Thanks. By curiosity, would it be possible to have somehow a symmetrical behavior such that a is also actualized if b is changed ?
@Aderam Yes you can, you can create a setter for b as well. I sugget you read up on property, it's very useful in a whole bunch of cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.