如何在numpy函数中使用numpy类型的子类?

nlejzf6q  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(118)

我有一个Python3.8程序,我正在使用它制作一个数独游戏,供我自己娱乐(底部有代码和注解)。许多数独实用程序实现了一种向给定单元格添加注解的方法,以便跟踪游戏。我选择使用 numpy ,但是添加此noting功能需要添加 set 给每个细胞。我试图通过创建一个具有 set 捆绑在其中以跟踪注解。
然而,这并没有起作用,因为似乎我试图在任何类型中使用我的类 numpy 的函数导致它们忽略我的类,而使用父类。我甚至试着不让我的类成为任何类的子类 numpy 的类型,但这只是导致它使用 object 作为类型。
我试着用 numpy.dtype 创建我自己合法的方法 dtype 然而,根据我的理解,我不能嵌入一个合适的python set 其中一个。我的其他选择是嵌入一个静态 N x 1 我的自定义数据类型中的数组(我认为这不是特别有效),或者只需嵌入另一个单元格网格即可 sets 在内部这两个似乎对我都不是特别有吸引力。
有什么方法可以做到这一点吗 numpy ,还是有更适合我的方法?


# !/usr/bin/python3

import numpy as np

class ByteWithSet(np.uint8):
    def __new__(cls, *_,**__):
        print("Creating new ByteWithSet")
        return super(ByteWithSet, cls).__new__(cls, *_,**__)
    def __init__(self):
        print("Initializing ByteWithSet")
        self._set = set()
    def is_fancy(self):
        return True

arr = np.zeros(shape=[2,2], dtype=ByteWithSet)
for el in arr.flatten():
    print(el, type(el))

for el in arr.flatten():
    print(el.is_fancy())

"""
This prints:
> 0 <class 'numpy.uint8'>
> 0 <class 'numpy.uint8'>
> 0 <class 'numpy.uint8'>
> 0 <class 'numpy.uint8'>

...Error stuff...
AttributeError: 'numpy.uint8' object has no attribute 'is_fancy'
"""

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题