Search code examples
pythonclassvariablescalculatorstatements

Calculator: Name Error in Python class


I'm building a calculator. I'm getting the "NameError: name 'self' is not defined the statement "if self.op.Pending == True" part of my code. I tried setting something equal to None, but that didn't get rid of the error. How do I get rid of the error?

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())

Solution

  • self is not defined outside of your individual functions, which is why in each function you have to call def func(self...):

    Thus, call that in a function:

    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())