在索引切片的同时使用内置的setattr

时间:2015-01-11 20:09:20

标签: python numpy slice setattr

我写的一个类需要使用存储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的上述用法都没有产生我想要的行为,这对于d.x来说是一个带有条目[8,8,8,0,0]的5元素numpy数组。是否可以使用setattr执行此操作?

1 个答案:

答案 0 :(得分: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]