searchsorted - 全局名称"x"未定义

3

我尝试使用名为searchsortednumpy方法,但我无法使其工作。

以下是代码:

class Object(QMainWindow):
  def __init__(self):
    QMainWindow.__init(self)

    self.figure_canvas = FigureCanvas(Figure())
    self.axes = self.figure_canvas.add_subplot(111)

    x = np.arange(0.0, 5.0, 0.01)
    y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))
    self.axes.plot(x, y, "-", picker = 5)
    self.axes.set_ylim(-2, 2)

  def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax)

当我尝试构建这段代码时,出现以下错误:

NameError: global name 'x' is not defined

问题在哪里?我定义了要使用的x,但它显示未被定义。

希望你能帮助我。


缺少一个 ) - pp_
变量x只在__init__函数中声明,但对于onselect()函数不可见。 - Jordy Cuan
3个回答

2

您在__init__方法中定义了一个x,但是您的onselect方法没有定义x

如果您想在该实例的其他方法中使用该x,可以这样做:

self.x = np.arange(0.0, 5.0, 0.01) # this is in __init__

然后在onselect方法中,您可以使用self.x来引用它。


2

你只在__init__()函数的范围内定义了局部变量x,因此它无法在此范围外访问。

如果改为使用self.x设置x为实例属性,则可以通过self.x再次在onselect()类方法中访问它:

class Object(QMainWindow):
  def __init__(self):
    QMainWindow.__init(self)

    self.figure_canvas = FigureCanvas(Figure())
    self.axes = self.figure_canvas.add_subplot(111)

    self.x = np.arange(0.0, 5.0, 0.01)
    y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))
    self.axes.plot(x, y, "-", picker = 5)
    self.axes.set_ylim(-2, 2)

  def onselect(self, xmin, xmax):
    indmin, indmax = np.searchsorted(self.x, (xmin, xmax)

@PabloFlores 确保 onselect() 是一个类方法,通过在你的类中定义它并传递 self 参数来实现。 - gtlambert
你可以直接使用 self.onselect(xmin, xmax) 调用它 - 你不需要显式地传递 self 参数。 - gtlambert
非常感谢您的回答和帮助。但是我还需要麻烦您一件事。如果我写了 self.onselect(xmin, xmax),我会得到以下错误:NameError: global name "xmin" is not defined。我想我在使用 xmax 时也会遇到同样的问题。 - Pablo Flores
同意 - 你需要传递xminxmax的值!不幸的是,我不知道它们代表什么... - gtlambert
我正在尝试使用类似上面代码的类来完成这个:http://matplotlib.org/examples/widgets/span_selector.html。 - Pablo Flores
显示剩余3条评论

1
在onselect()函数中没有声明x值。
尝试这样做:
def __init__(self):
  ...
  self.x = np.arange(0.0, 5.0, 0.01)

def onselect(xmin, xmax):
  indmin, indmax = np.searchsorted(self.x, (xmin, xmax)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接