【问题标题】:Issues with classes in Python 3: class doesn't recognize variable that was declared within itPython 3 中的类问题:类无法识别在其中声明的变量
【发布时间】:2014-04-18 03:49:23
【问题描述】:

我正在用 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'

Main 类中有一个名为self.a 的变量,所以我不知道为什么它不能识别它。

【问题讨论】:

  • 如果你只有一个巨大的函数,你甚至不应该为此使用一个类。只需使用一个功能。此外,您将很难以这种方式进行操作。请参阅 pyparsing 以了解此操作是否正确。
  • 嗨,我使用类的原因是因为我希望以后能够轻松地添加到它。例如,我想在完成这部分工作后添加做基本代数的能力。
  • 它仍然不是一个有效的类。它定义了一个“主要”对象,不管它是什么。试着找到关于班级设计的好教程。以后你会感谢自己的。
  • 好的,谢谢你的建议;)

标签: python class python-3.x calculator self


【解决方案1】:

这是因为self.a 是在条件if 语句中分配的,实际上是其中2 个。所以如果这两个条件都不满足,self.a 永远不会被赋值,当你尝试使用它来计算 self.c 时会抛出错误

尝试在条件之前将self.aself.b设置为默认值(可能为0),那么如果条件不满足,它至少会有一个默认值。

-- 编辑--

实际上,对于这种情况,您可能不想只将它们分配给 0。但您需要确保在尝试使用它们之前以某种方式定义它们。

【讨论】:

    猜你喜欢
    • 2021-05-07
    • 2021-06-21
    • 2011-06-11
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多