2

我正在编写的一个类需要使用存储 numpy 数组的变量名属性。我想为这些数组的切片分配值。我一直在使用 setattr,以便我可以让属性名称有所不同。我为切片赋值的尝试如下:

class Dummy(object):
        def __init__(self, varname):
        setattr(self, varname, np.zeros(5))

d = Dummy('x')
### The following two lines are incorrect
setattr(d, 'x[0:3]', [8,8,8])
setattr(d, 'x'[0:3], [8,8,8])

setattr 的上述两种用法都不会产生我想要的行为,即 dx 是一个包含条目 [8,8,8,0,0] 的 5 元素 numpy 数组。可以用 setattr 做到这一点吗?

4

1 回答 1

3

想想你通常会如何编写这段代码:

d.x[0:3] = [8, 8, 8]
# an index operation is really a function call on the given object
# eg. the following has the same effect as the above
d.x.__setitem__(slice(0, 3, None), [8, 8, 8])

因此,要进行索引操作,您需要获取名称所引用的对象x,然后对其执行索引操作。例如。

getattr(d, 'x')[0:3] = [8, 8, 8]
于 2015-01-11T20:27:09.180 回答