如何在没有子类化numpy.ndarray的情况下编写一个行为类似于numpy.ndarray的类?

时间:2012-02-29 12:22:14

标签: python numpy

让我们假设以下给定的类定义:

class Numeric(object):
  def __init__(self, signal):
    self.signal = signal

现在,由于要求Numeric不从numpy.ndarray继承,我如何扩展Numeric表现得像numpy.ndarray的定义?

修改 signal应为np.ndarray(或类似quantities.Quantity)。我有以下的想法:

import numpy as np
import quantities as pq

a = Numeric(pq.Quantity([1,2,3], 'mV'))
b = Numeric(pq.Quantity([1,3,5], 's'))
c = Numeric(np.array([10,20,30]))

a = Numeric(np.array([1,2,3]))
b = Numeric(np.array([1,3,5]))
a * c
a * b
a * np.array([3,4,5])

和:

import matplotlib.pyplot as plt
plt.plot(b)

1 个答案:

答案 0 :(得分:1)

使用装扮器调整numpy - 函数以及__array__ Numeric的实现,我可以解决大多数问题:

def adapt_signal_functions(cls):
  def generateAdjustedFunction(functionName):
    print functionName
    def foo(self, *args, **kwargs):
      function = getattr(self.signal.__class__, functionName)
      return function(self.signal, *args, **kwargs)
    return foo
  functionNames = [
      '_get_units',
      '_set_units',
      'rescale',
      'ptp',
      'clip',
      'copy',
      'compress',
      'conj',
      'cumprod',
      'cumsum',
      'diagonal',
      'dot',
      'flatten',
      'getfield',
      'round',
      'trace',
      'max',
      'mean',
      'min',
      'newbyteorder',
      'prod',
      'ravel',
      'reshape',
      'resize',
      'round',
      'std',
      'sum',
      'trace',
      'transpose',
      'var',
      '__getitem__',
      '__getslice__',
      '__abs__',
      #
      '__add__',
      '__div__',
      '__divmod__',
      '__floordiv__'
      '__mod__',
      '__mul__',
      '__pow__',
      '__sub__',
      #
      '__radd__',
      '__div__',
      '__divmod__',
      '__rfloordiv__',
      '__rmod__',
      '__imul__',
      #'__rmul__',
      '__rpow__',
      '__rsub__',
      ]
  for functionName in functionNames:
    foo = generateAdjustedFunction(functionName)
    setattr(cls, functionName, foo)
  return cls


@adapt_signal_functions
class Numeric(object):
  def __init__(self, signal):
    self.signal = signal
    self.adapt_quantity()

  def adapt_quantity(self):
    if hasattr(self.signal, '_dimensionality'):
      self._dimensionality = self.signal._dimensionality
      self.dimensionality = self.signal.dimensionality

  def __array__(self):
    return self.signal

我能做到:

import numpy as np
import quantities as pq

a = Numeric(pq.Quantity([1,2,3], 'mV'))
b = Numeric(pq.Quantity([1,3,5], 's'))
c = Numeric(np.array([10,20,30]))
n =  np.array([1,2,3])

a * a
a * c
a * n
a.max()

print type(a * n) == type(a.signal *  n)
# >>> True
print type(a * c) == type(a.signal *  c.signal)
# >>> True

返回类型对应于Numeric.signal的等效返回类型。

仍然存在一个问题:

print type(n * a) == type(n * a.signal)
# >>> False

任何想法,如何解决这个问题?