0

I have two classes

class A():
    def __init__(self):
        self.a = 1

class B():
    def __init__(self):
        self.b = 2
        self.A = A()
        self.A.a = self.b

and one class contains the other as an instance (maybe inheritance would be better?). I want some properties, say a, of that A instance to be synced some properties of the containing B instances, say b. So in this example

B_instance = B()
print(B_instance.A.a)
B_instance.b=3
print(B_instance.A.a)

the first print statement gives 2 and the second one I want to give 3. But it gives 2, despite python passing by reference name.

Marlo
  • 207
  • 1
  • 4
  • 12

1 Answers1

1

An example using property. Try this:

class A():
    def __init__(self):
        self.a = 1

class B():
    def __init__(self):
        self.A = A()
        self.b = 2

    def set_b(self, value):
        self._b = value
        self.A.a = self._b
    def get_b(self):
        return self._b
    b = property(get_b, set_b)

B_instance = B()
print(B_instance.A.a)
B_instance.b = 3
print(B_instance.A.a)

Output:

2
3
abhiarora
  • 9,743
  • 5
  • 32
  • 57