Reputation: 533
In my current project, I have an object with many variables, some of which I want to organize into a new vector (more specifically: a one-dimensional numpy array; the constituent variable entries are scalars). I then wish to apply some mathematical operations to this vector, and automatically update the original variables accordingly.
Note: I am aware that I could simply overwrite the original variables with the updated vector entries. I would like to avoid this. Also note that I cannot simply keep the vector as the source for all scalar variables, as it is created after some of its constituent variables are used. I am looking for a more elegant solution through a two-way link between the entries in the vector and their original variables, so any change to either is mirrored by the other.
Is something like this possible in Python?
Here is a Python example which does not do what I want:
import numpy as np
# Define three variables
a = 5
b = 3
c = 2
# Create a vector which points to these variables
v = np.asarray([a,b,c])
# Print the vector
print(v)
# Update the vector
v = v*2
# Print the vector
print(v)
# Print the original variables. Should be:
# a = 10
# b = 6
# c = 4
# Actually is:
print('a = '+str(a))
print('b = '+str(b))
print('c = '+str(c))
Upvotes: 0
Views: 53
Reputation: 2569
The objects you are working with (int, float..) are immutable, so they don't get updated, they must be replaced anyway.
All in all the solution will be one of the two options, you already mentioned. Either overwrite the variables or create the numpy array early and work on it from the beginning.
However, this behavior can be encapsulated:
Option 1: Replacing the variables, encapsulating the vector and work only on the variables:
def vector_calculation(a, b, c):
v = np.asarray([a,b,c])
v = v*2
return v.tolist()
a = 5
b = 3
c = 2
a, b, c = vector_calculation(a, b, c)
Option 2: Creating the vector early and work entirely on the array:
v = np.asarray((0,0,0))
v[0] = 5 # work with these like with
v[1] = 3 # individual variables
v[2] = 2
v = v*2
Option 2a: Create a class for more comfort:
class Vector:
def __init__(self):
self.v = np.asarray((0,0,0))
@property
def a(self):
return self.v[0]
@a.setter
def a(self, val):
self.v[0] = val
@property
def b(self):
return self.v[1]
@b.setter
def b(self, val):
self.v[1] = val
@property
def c(self):
return self.v[2]
@c.setter
def c(self, val):
self.v[2] = val
vari = Vector()
vari.a = 5
vari.b = 3
vari.c = 2
vari.v = vari.v * 2
print(vari.a, vari.b, vari.c)
Upvotes: 1