Home > Software design >  BaseClass not change their value, if it change it in MainClass
BaseClass not change their value, if it change it in MainClass

Time:12-25

So i have the problem: I put some numbers in variable on A class, create B class with another variable and equate them, but if I change A class variable they don't change in B class, output is still "123", maybe there is a option that can make B var change whenever change A var?

class A:
    def __init__(self):
        self.a = 123
Aa = A()

class B(A):
    def __init__(self, A):
        self.b = Aa.a
Bb = B(A)   

print(Bb.b)
c = int(input("Numbers: "))
Aa.a = c
print(Bb.b)

I tried a different def functions but they didn't work

CodePudding user response:

What you're doing is exactly the same as this:

i = 7
j = i
i = 9
print(j)

Would you expect j to print 9? It won't because j is still bound to the 7 object.

CodePudding user response:

What I think you want is a @property -- a method that acts like an attribute (every time you access the attribute, Python calls it as a method and returns the result). This allows you to have an attribute that automatically references some other value or computes its own dynamic value rather than being a normal variable.

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

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

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


Aa = A()
Bb = B(Aa)
print(Bb.b) # 123
Aa.a = 42
print(Bb.b) # 42

Note that each B object has a reference to an A object, but it is not necessary (or desirable) for B to itself be a subclass of A. You generally want to use composition (has a) or inheritance (is a), not both at once. In this case, composition makes more sense.

  • Related