Python 3 中类的问题:类无法识别内部声明的变量

1 投票
1 回答
1192 浏览
提问于 2025-04-18 03:13

我正在用Python 3创建一个计算器,你可以输入完整的算式,比如:
3 + 2
或者
5 * 2
我希望它能仅根据这些信息进行计算。
这是我目前写的代码:

# calc.py

import os

class Main:
    def calculate(self):
        # At the moment, \/ this is not in use.
        self.alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        self.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        self.operators = ['+', '-', '*', '/']
        self.prob = input('>>>')
        os.system('cls')
        self.prob.split()
        self.num = 'a'
        for i in range(0, len(self.prob) - 1):
            if self.prob[i] in self.numbers:
                if self.num == 'a':
                    self.a = int(self.prob[i])

                if self.num == 'b':
                    self.b = int(self.prob[i])

            if self.prob[i] in self.operators:
                self.operator = self.prob[i]
                self.num = 'b'

            if self.prob[i] == ' ':
                pass

        if self.operator == '+':
            self.c = self.a + self.b

        elif self.operator == '-':
            self.c = self.a - self.b

        elif self.operator == '*':
            self.c = self.a * self.b

        elif self.operator == '/':
            self.c = self.a / self.b

        print(self.c)
        os.system('pause')
        os.system('cls')        

main = Main()

main.calculate()

但是它给我报了下面的错误:

    Traceback (most recent call last):
  File "C:\Python33\Programs\calc.py", line 48, in <module>
    main.calculate()
  File "C:\Python33\Programs\calc.py", line 31, in calculate
    self.c = self.a + self.b
AttributeError: 'Main' object has no attribute 'a'

在主类中有一个叫 self.a 的变量,所以我不明白为什么它不认识这个变量。

1 个回答

0

这是因为 self.a 是在一个条件语句 if 中被赋值的,实际上有两个这样的条件。所以如果这两个条件都没有满足,self.a 就永远不会被赋值,当你试图用它来计算 self.c 时,就会出现错误。

你可以尝试在条件语句之前给 self.aself.b 设置一个默认值(比如0),这样即使条件没有满足,它们至少也会有一个默认值。

-- 编辑 --

其实在这种情况下,你可能不想直接把它们赋值为0。但你需要确保在使用它们之前,它们已经被定义过。

撰写回答