如何使用numpy数组的字段初始化对象,并将该数组作为参数传递? [英] How to initialize an object with a field a numpy array, and the array is passed as an argument?

查看:50
本文介绍了如何使用numpy数组的字段初始化对象,并将该数组作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用numpy数组的字段初始化一个对象,并将该数组作为参数传递?

How to initialize an object with a field a numpy array, and the array is passed as an argument?

例如

class Foo
    def __init__()
        self.x = None
        self.m = None
        self.v = None

这里有静态方法

@staticmethod
def pop_x(x):
     # populate x with zeros
     x = zeros(n)

如果我说 self.pop(self.x) 将不起作用,因为设置 x= 它只是丢失了对 x

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)

因为我有一堆字段 Object.x, Object.y, ... 所以我不想为每个字段创建一个 pop 方法.

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, :]

这里 pop_q 不起作用,因为设置 q 等于 numpy 数组丢失对 q 的引用.

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.

也许您可以将数组放入一个 dict 并将该 dict 连同数组的名称一起传递给您的泛型函数,这将是 dict 中的键?

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?

由于类中的字段也在 dict 中,该方法也适用于类实例,使用 object.__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.

这篇关于如何使用numpy数组的字段初始化对象,并将该数组作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆