计算器:Python类

时间:2016-03-27 21:26:28

标签: python class variables calculator statements

我正在建造一个计算器。我得到了" NameError:name' self'没有定义语句"如果self.op.Pending == True"我的部分代码。我尝试设置等于None的东西,但那并没有消除错误。我如何摆脱错误?

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

2 个答案:

答案 0 :(得分: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个空格

答案 1 :(得分: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())