2016-03-27 32 views
0

我正在構建一個計算器。我得到了「NameError:name'self'沒有定義聲明」if self.op.Pending == True「的一部分代碼。我嘗試設置一些等於None的東西,但那並沒有擺脫錯誤。我該如何擺脫錯誤的?計算器:Python類中的名稱錯誤

class calculator(): 
    def __init__(self): 
     self.total = 0 
     self.current = "" 
     self.newNumber = True 
     self.opPending = False 
     self.op = "" 
     self.eq = False 

    def numberPress (self, num): 
     self.eq = False 
     temp = textbox.get() 
     temp2 = str(num) 

    if self.newNumber: 
     self.current = temp2 
     self.newNumber = False 
    else: 
     if temp2 == '.': 
      if temp2 in temp: 
       return 
      self.current = temp + temp2 
      self.display(self.current) 

    def calcTotal(self): 
     self.eq = True 
     self.currrent = float(self.current) 

    if self.opPending == True: #ERROR 
     self.doSum() 
    else: 
      self.total = float(textbox.get()) 

回答

0

self不是你個人的功能之外定義的,這就是爲什麼在每一個功能你必須調用def func(self...):

因此,調用一個函數:

class calculator(): 
    def __init__(self): 
     self.total = 0 
     self.current = "" 
     self.newNumber = True 
     self.opPending = False 
     self.op = "" 
     self.eq = False 

    def numberPress (self, num): 
     self.eq = False 
     temp = textbox.get() 
     temp2 = str(num) 

     if self.newNumber: 
      self.current = temp2 
      self.newNumber = False 
     else: 
      if temp2 == '.': 
       if temp2 in temp: 
        return 
       self.current = temp + temp2 
       self.display(self.current) 

    def calcTotal(self): 
     self.eq = True 
     self.currrent = float(self.current) 

    def call(self): 
     if self.opPending == True: #ERROR 
      self.doSum() 
     else: 
      self.total = float(textbox.get()) 
+0

謝謝,無法相信我忘了臺詞!現在,我有時間來構建GUI。 – user6067378

+0

@ user6067378祝你好運! –

1

這是因爲您有縮進錯誤:

這一切,對numpress計數:

def numberPress (self, num): 
     self.eq = False 
     temp = textbox.get() 
     temp2 = str(num) 

而下一行是 「」 的功能:

if self.newNumber: 
     self.current = temp2 
     self.newNumber = False 
    else: 
     if temp2 == '.': 
      if temp2 in temp: 
       return 
      self.current = temp + temp2 
      self.display(self.current) 

同樣的事情發生在def calcTotal(self):

爲了解決這個問題,你只需要4個空格添加到是「