numpython类调用了错误的\uyu setitem__

2024-10-02 12:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下课程:

class autoArray2(numpy.ndarray):
    def __new__(self, *args, **kwargs):
        obj = numpy.array(*args, **kwargs)
        return(obj)

    def __setitem__(self, coords, value):
        print("HERE")

但是似乎调用的是array.__setitem__,而不是我指定的那个。在

^{pr2}$

“这里”不打印。在


Tags: selfnumpyobjnewreturndefargscoords
1条回答
网友
1楼 · 发布于 2024-10-02 12:36:27

子类化numpy数组有点棘手。 Stefan van der Walt's slides和{a2} 如果你想子类化的话,这是一个很好的开始。在

import numpy as np

class AutoArray2(np.ndarray):
    def __new__(cls, input_array):
        # Input array is an already formed ndarray instance
        # We first cast to be our class type
        obj = np.asarray(input_array).view(cls)
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
    def __setitem__(self, coords, value):
        print("HERE")

a = np.array([[1,2],[2,3]])
b = AutoArray2(a)
b[0,0] = 1

收益率

^{pr2}$

关键因素是对view(cls)的调用。如果没有它,您将返回一个普通的ndarray,而不是AutoArray2实例。在

而且,a[0,0] = 1正在使用a原版ndarray。要使用b__setitem__,您需要b[0,0] = 1。在

相关问题 更多 >

    热门问题