I would like to create dependence between some parameters of instances (not necessarily of the same class as in example). I came up with folowing code, which worked until I decided to move it into module and use it by importing.
class objectD(object):
def __init__(self,val1,val2,val3):
self.val1 = val1
self.val2 = val2
self.val3 = val3
def __str__(self):
return str(str(self.val1)+","+str(self.val2)+","+str(self.val3))
def dependence(self,dependent):
print "values val1 and val2 of "+str(self)+" now depend on "+dependent
self.val1 = eval(dependent).val1
self.val2 = eval(dependent).val2
self.dependent = dependent
def update(self):
self.val1 = eval(self.dependent).val1
self.val2 = eval(self.dependent).val2
#test
obj1 = objectD(350,4,500)
print obj1
obj2 = objectD(230,1,1000)
print obj2
obj2.dependence("obj1")#problem with imported class occurs there
print obj2
obj1.val1 = 1315
obj1.val2 = 6464
print obj1
obj2.update()
print obj2
Problem seems to be in assigning dependence to instance which by using imported version of the class simply does not exist according to python. It seems to me, that calling method dependence() on instance goes on in module and not in my script.
Is there a way to fix the import somehow, or perhaps some different approach to creating dependencies?
There should be no need for
eval. Why not simply do this instead?This will work as expected, because
dependentmerely stores a reference toobj1, not the state of the object itself. So the call toupdate()will actually pull the new values.