简体   繁体   中英

Issues with classes in Python 3: class doesn't recognize variable that was declared within it

I am creating a calculator in Python 3 in which you can type a full problem such as: 3 + 2 or 5 * 2 And I want it to be able to calculate just from that info. Here is the code I already have:

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

It's giving me the error below:

    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'

There is a variable named self.a in the Main class, so I'm not sure why it doesn't recognize it.

It's because self.a is assigned within a conditional if statement, 2 of them in fact. So if both of those conditions aren't met, self.a is never assigned, and an error is thrown when you try to use it to calculate self.c

Try setting self.a and self.b to a default value (maybe 0) before the conditional, then if the condition isn't met, it will at least have a default value.

-- EDIT --

actually, for this case you probably don't want to just assign them to 0. But you need to make sure they are defined somehow before you try to use them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM