如何实现__getitem__,以便它可以处理输入参数,然后将它们传递到底层的numpy数组中?

dw1jzc5e  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(124)

假设A是一个简单的Python类,它有一个成员self._mat,它是一个numpy数组。A的构造函数得到一个整数n,并创建一个内部n乘n零的numpy数组,并将其保存为私有成员self._mat。
我如何实现__getitem__,以便我可以首先预处理传递给__getitem__的参数(例如将某些字符串,如序列化的IDMap到从零开始的整数索引),然后将它们传递到内部numpy数组self._mat,以便它将以与类的用户直接将处理后的参数直接传递到内部numpy数组相同的方式进行处理?
A的一个示例(坏的)实现看起来像这样:

class A():
     def __init__(self, n: int=3):
         self._mat = np.zeros(shape=[n, n])
     def __getitem__(self, val):
         # This implementation is wrong and doesn't pass interpretation...
         val = _process_val(val)  # How do I process this correctly such that I look at the inner elements of each index in the POSSIBLE multi-index as well?
         return self._mat[val]

示例用法:

a = A(n=4)
print(a[0], a[0, 1], a[(0, 1)], a[:, 1:2])
# Lets say that the string 'deadbeef' is cast onto the integer 0
print(a['deadbeef'], a['deadbeef', 1], a[('deadbeef', 1)], a[:, 'deadbeef':2])
jdgnovmf

jdgnovmf1#

基本的思想可以用递归来解决-改变你想要的所有元素,同时保持参数的一般结构。

import numpy as np

def process_arg(arg):
    if isinstance(arg, str):
        if arg == "deadbeef":
            return 0
    if isinstance(arg, tuple):
        return tuple(process_arg(a) for a in arg)
    else:
        return arg

class A():
    def __init__(self, n: int=3):
        self._mat = np.zeros(shape=[n, n])
    def __getitem__(self, arg):
        arg = process_arg(arg)
        return self._mat.__getitem__(arg)

a = A(n=4)
print(a[0], a[0, 1], a[(0, 1)], a[:, 1:2])
print(a['deadbeef'], a['deadbeef', 1], a[('deadbeef', 1)])

处理像a[:, 'deadbeef':2]中那样的切片,我将留给您作为练习。

相关问题