我写的一个类需要使用存储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执行此操作?
答案 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]