我试图在python2.x中构建简单的分数计算器
from fractions import Fraction
class Thefraction:
def __init__(self,a,b):
self.a = a
self.b =b
def add(self):
return a+b
def subtract(self,a,b):
return a-b
def divide(self,a,b):
return a/b
def multiply(self,a,b):
return a/b
if __name__=='__main__':
try:
a = Fraction(input('Please type first fraction '))
b = Fraction(input('Please type second fraction '))
choice = int(input('Please select one of these 1. add 2. subtract 3. divide 4. multiply '))
if choice ==1:
print(Thefraction.add(a,b))
elif choice==2:
print(Thefraction.subtract(a,b))
elif choice==3:
print(Thefraction.divide(a,b))
elif choice==4:
print(Thefraction.multiply(a,b))
except ValueError:
print('Value error!!!!!')
我不确定是否生成了可以实例化的正确类,但是我在__name__=='__main__'
的旁边使用了Thefraction.add
。我错过什么了吗?
你没有把
()
放在theFraction
对象前面。即使你这样做了,你也将面临另一场灾难..你用两个变量(a,b)初始化你的对象,这意味着你将像我不认为您需要这样做,因为a和
b
是每个方法中的局部变量。。这是一种你不需要的变量。 我想你想要的是这个。这是完整的代码
如果您想像使用它一样使用它,应该将类方法定义为@classmethod,而不需要init:
这种声明方法的方式表示它们不会在类的实例中运行,但可以如下调用:
应该这样做:
那么在你们班上:
等等。不要将
a
和b
作为参数包含在方法中。是的,再复习一遍关于课程的教程。彻底的。
相关问题 更多 >
编程相关推荐