2016-03-01 69 views
3

我試圖用numpy方法調用searchsorted,但我無法使其工作。searchsorted - 未定義全局名稱「x」

這是代碼:

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,但它表示它不是。

希望你能幫助我。

+0

存在丟失的')'。 –

+0

變量x剛剛在__init__函數中聲明,但對onselect()不可見( –

回答

2

只有你引用它定義__init__()函數範圍內的局部變量x,因此無法在此範圍之外訪問。

相反,如果你設置x是一個實例屬性使用self.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) 
+0

)緩慢地講,'x'是一個實例屬性,而不是這裏的類屬性。 – Gerrat

+0

我試過了。當我寫'self.x'時,我必須在'''''變量'和'self.axes.plot()'中這樣寫。但在這個時候,我得到的錯誤:'名稱錯誤:全局'自己'沒有定義' –

+0

@PabloFlores確保'onselect()'是一個類方法,通過在你的類中定義它並將它傳遞給'self'參數 – gtlambert

1

在ONSELECT()funtion有IR沒有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) 
2

你在你的__init__方法定義的x。您onselect沒有x定義

如果你想使用x在該實例的其他方法,你可以做

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

然後在onselect可以使用self.x