我想寫一個可以解決算術運算的代碼。這些類mult
和plus
是爲了解決類似的問題:如何在類屬性上使用算術運算?
e1 = mult(const(3),const(4))
e1 = plus(const(3),const(4)
並返回結果(分別爲12和7)。
現在從講師的分配要我們寫一個能解決程序類似這樣的問題:
e1 = mult(plus(const(3),const(4)),const(5)) # should print 35
e2 = plus(mult(const(3),const(4)),const(5)) # should print 12
我試圖解決在使用列表中的問題,以便常量存儲在列表(即store_const
),那麼類mult(const(n),const(n))
和plus(const(n),const(n))
將解決日問題並返回結果。我的問題是爲每個類mult
/plus
,我創建了添加或乘以store_const[0]
和[1]
的方法eval
,但我每次運行該程序:E1返回12和e2回報7
我想這是因爲mult
/plus
只需要store_const[0] = 3
和store_const[1] = 4
,並省略store_const[2] = 5
。
所以,我怎麼能解決這個問題:
e1 = mult(plus(const(3),const(4)),const(5))
其中plus
的結果存儲爲新const(n)
,然後mult
類能夠執行來產生35K
這裏是我的代碼:
class expr(object): #ignore class
pass
class const(expr):
store_const = [] #list to store constants
def __init__(self, n): #initial constructor
self.n = n
const.store_const.append(self.n) #store constants in list
class binOp(expr): #sublcass of expr
def __init__(self, expr1, expr2): #initial constructor arguments
self.expr1 = expr1
self.expr2 = expr2
class mult(binOp):
def __int__(self, *args):
super(mult, self).__init__(*args) #inheriting the superclass constructor arguments
def eval(self):
self.expr1 = const.store_const[0]
self.expr2 = const.store_const[1]
self.result = self.expr1 * self.expr2
return self.result
class plus(binOp):
def __init__(self, *args):
super(plus, self).__init__(*args) #inheriting the superclass constructor arguments
def eval(self):
self.expr1 = const.store_const[0] #assigning the 1st elem of list to expr1
self.expr2 = const.store_const[1] #assigning the 2nd elem of list to expr2
self.result1 = self.expr1 + self.expr2
return self.result1
#input
e1 = mult(plus(const(3), const(4)),const(5))
print e1.eval()
e2 = plus(mult(const(3), const(4)),const(5))
print e2.eval()
#output
12
7
噢好吧,我現在明白了,因爲我也在考慮如何將expr1和expr2直接分配給const(n)。 – 2014-10-30 15:04:54
如果我想用str方法打印常量,即打印str(e1)=(3 + 4)* 5和打印str(e2)=(3 * 4)+5,該怎麼辦?因爲使用你的方法str(e1)= 7 * 5和str(e2)= 12 + 5 – 2014-10-30 15:45:55
每個類都應該有一個'__repr__'方法返回它的字符串表示。確保你的binOp類在參數上調用'repr',而不是'eval'。 – Kevin 2014-10-30 15:47:53