【发布时间】:2016-06-10 22:57:28
【问题描述】:
我正在尝试在 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。我错过了什么?
【问题讨论】:
-
你为什么要使用这样的方法?您是否考虑过遵循结构化 Python OOP 教程?
-
您可以使用
@staticmethod装饰器并将 a 和 b 放入参数中以进行添加。 -
在你使用
@staticmethod装饰器的时候,你也可以放弃__init__方法。在您删除__init__方法时,您不妨将它们设为函数而不是方法。 -
他不是在问如何简化或改进他的代码,而是在问如何正确地实例化一个类。
-
可以,只是少了几步!
标签: python instantiation