【问题标题】:How to write a subclass of numpy.ndarray which only takes complex values?如何编写一个只接受复数的 numpy.ndarray 的子类?
【发布时间】:2021-03-26 22:13:12
【问题描述】:

我想创建一个 numpy.ndarray 的子类,它是一个复数数组。为此,我试图使我的子类的构造函数返回一个 (0+0j) 的数组。我暂时不成功... 到目前为止,这是我的代码:

import numpy as np


class ComplexArray(np.ndarray):
    def __init__(self, args):
        np.ndarray.__init__(args, dtype=complex)
        self.fill(0)


a = ComplexArray(3)
a[0] = 1j

当我运行上面的代码时,我得到了错误TypeError: can't convert complex to float

我指定我要创建这样一个子类的原因是我以后想在其中实现几个方法。

提前感谢您的建议!

【问题讨论】:

    标签: python-3.x subclass numpy-ndarray dtype


    【解决方案1】:

    我找到了解决办法:

    import numpy as np
    
    
    class ComplexArray(np.ndarray):
        def __new__(cls, n):
            ret = np.zeros(n, dtype=complex)
            return ret.view(cls)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-09
      • 2011-02-24
      • 2014-12-13
      • 2016-07-07
      • 2019-09-14
      • 2012-09-08
      • 1970-01-01
      • 2013-08-15
      相关资源
      最近更新 更多