I would like to connect two variables totwo different classes but I don't know if what I'm trying to do is possible or not.
for instance, if I have those two classes:
class one():
def __init__(self):
self.a = 0
def compute(self):
self.a = self.a + 1
class two():
def __init__(self):
self.a = 0
self.C_one = one()
self.link()
def link(self):
self.a = self.C_one.a
def compute(self):
self.C_one.compute()
print('C_one a=',self.C_one.a )
print('C_two a=',self.a )
C_two = two()
for i in range(5):
C_two.compute()
In the class two
I would like connect the variable a
with the variable a
of class one
, so I don't have to explicitly call self.a = self.C_one.a
each time I execute C_two.compute
The code in example give me this:
C_one a= 1
C_two a= 0
C_one a= 2
C_two a= 0
C_one a= 3
C_two a= 0
C_one a= 4
C_two a= 0
C_one a= 5
C_two a= 0
Which is not the result I expect. Somebody know if I can do that in python?
From the example below
class one():
def __init__(self):
self.a = 0
def compute(self):
self.a = self.a + 1
class two():
def __init__(self):
self.a = 0
class three():
def __init__(self):
self.C_one = one()
self.C_two = two()
self.b = 0
def compute(self):
self.C_one.compute()
#self.C_two.a = self.C_one.a
print('C_one a=',self.C_one.a )
print('C_two a=',self.C_two.a )
C_three = three()
for i in range(5):
C_three.compute()
is it possible to use the answer of deceze and replace the commented line #self.C_two.a = self.C_one.a
with a property ? Like that classes one
and two
are linked in the class three
.
class one():
def __init__(self):
self.a = 0
def compute(self):
self.a = self.a + 1
class two():
def __init__(self,one):
self.C_one = one
@property
def a(self):
return self.C_one.a
class three():
def __init__(self):
self.C_one = one()
self.C_two = two(self.C_one)
self.b = 0
def compute(self):
self.C_one.compute()
print('C_one a=',self.C_one.a )
print('C_two a=',self.C_two.a )
C_three = three()
for i in range(5):
C_three.compute()
Define two.a
as a property
:
class two:
def __init__(self):
self.C_one = one()
@property
def a(self):
return self.C_one.a
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With