【发布时间】: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