This question is an exact duplicate of:
How to initialize an object with a field a numpy array, and the array is passed as an argument?
For example
class Foo
def __init__()
self.x = None
self.m = None
self.v = None
this has static methods
@staticmethod
def pop_x(x):
# populate x with zeros
x = zeros(n)
wouldn't work if I say self.pop(self.x)
because set x=
something it's just losing the referenced to x
def pop_x():
# populate x with zeros
self.x = zeros(n)
because I have a bunch of fields Object.x, Object.y, ...
so I don't want to make a pop
method for each of them.
@staticmethod
def update_q(q, i, val):
"""
update i-th quantity
"""
if q.ndim == 1:
q[i] = val
elif q.ndim == 2:
q[i, :] = val
@staticmethod
def pop_q(q, n, m):
"""
populate quantity with zeros
"""
if q.ndim == 1:
q = zeros(n)
elif q.ndim == 2:
q = zeros((n, m))
@staticmethod
def get_q(q, i):
if q.ndim == 1:
return q[i]
elif q.ndim == 2:
return q[i, :]
Here pop_q wouldn't work because setting q equals a numpy array lose the reference to q.
This sounds like you may need a different design alltogether, e.g. separate the object that holds all those arrays from the object that does the calculations.
Maybe you could just put the arrays in a dict and pass the dict to your generic function, together with the name of the array, which would be the key in the dict?
Since the fields in a class are also in a dict, that approach can work with a class instance as well, using
object.__dict__
and using string names instead of variables.