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

Use built-in setattr simultaneously with index slicing

A class 我写的需要使用变量名属性存储 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 做到这一点吗?

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

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]