This question is an exact duplicate of:
- How to make up lost reference to declare a field (numpy)? 2 answers
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.