python - Python分数类和菜单选项
问题描述
我正在制作一个具有可在菜单选项中调用的函数的类,供用户选择诸如添加分数之类的操作。我试图在菜单选项中调用诸如 def__add__(self, other) 之类的函数,但它不起作用。如何从类分数中调用这些函数?是 self.add() 吗?
def gcd(a,b):
if a == 0:
return b
else:
return gcd(b % a, a)
c = gcd(15,21)
print (c)
class fraction:
def __init__ (self, numerator, denominator):
gcd = hcf(numerator, denominator)
self.top = numerator/gcd
self.bottom = denominator/gcd
def __str__(self):
if self.bottom == 1:
return str(self.top)
elif self.top > self.bottom:
return str(self.top//self.bottom) +str(fraction(self.top % self.bottom,self.bottom ))
else:
return str(self.top) + "/ " + str(self.bottom)
def __add__(self, other):
newTop = self.top + other.bottom + other.top * self.bottom
newBottom = self.bottom + other.bottom
return fraction(newTop, newBottom)
def multiply(self):
return fraction(2*self.top, self.bottom)
def multiply_by(self, n):
return fraction(n * self.top, self.bottom)
def __sub__(self,other):
newTop = self.top - other.bottom - other.top * self.bottom
newBottom = self.bottom - other.bottom
return fraction(newTop, newBottom)
def __mul__(self,other):
newTop = self.top * other.top
newBottom = self.bottom * other.bottom
return fraction(newTop, newBottom)
def __div__(self, other):
pass
def menu(self):
print("[1] Add two fractions")
print("[2] Subtract two fractions")
print("[3] Multiply two fractions")
print("[4] Divide two fractions")
print("[5] Add fraction to integer")
print("[6] Fraction subtract integer")
print ("[7] Fraction multiply by integer")
print ("[8] Fraction divided by integer")
print("[q] Exit program")
#menu()
option = input("Enter your option: ")
while option!= 'q':
if option == "1":
# a = fraction(15,21)
self.add(3,4) #call add function
print("option 1 has been called ")
elif option == 2:
#do stuff
print( "option 2 has been called")
elif option == 3:
#do stuff
print("option 3 has been called")
elif option ==4:
#do stuff
print("option 4 has been called")
elif option == 5:
#do stuff
print("option 5 has been called")
else:
print("Invalid option")
print()
menu()
option = input("Enter your option: ")
a = fraction(4,27)
print(a.multiply())
print(a.multiply_by(7))
print(a + fraction(2,7))
print(fraction(1,2) * fraction(3,7))
`
解决方案
您可以发布具体不起作用的内容吗?
我不确定您的“添加”功能是否正确(您不想添加“顶部”并乘以“底部”吗?),但您只需使用“+”号即可使用该功能,所以如果您具有正确的功能,这应该可以正常工作:
print(a + fraction(2,7))
推荐阅读
- javascript - Javascript 对象属性仅在从另一个函数内部调用时返回未定义
- angular - 我可以得到以前的值形式(更改)=“$event”吗?
- image-processing - 神经网络模仿行为研究
- javascript - 根据选择选项添加按钮以显示隐藏?
- python - 逆矩阵结果在 MATLAB 和 Python 中不同
- laravel - 通过 .htaccess / 异常管理位置 / 框架 Laravel 重定向到安全连接
- c# - 在 C# 中使用 Git TFS API 在一次提交中进行移动和编辑?
- stanford-nlp - 如何从文件中读取规则
- android - 如何将 Android Studio 项目导出到特定存储库中的新 GitHub 分支?
- java - 无法将功能作为内容添加到 Vogella Eclipse RCP 教程项目