2013-09-27 64 views
0

的方法時,我在Python裏是相當新的,所以我希望你能幫助我這個愚蠢的問題,因爲我無法找到任何原因發生這個問題。所以,我有一個名爲calcoo.py文件,其中有一個名爲計算器,總結和減去,然後我繼承叫CalculatorCHild(位於同一目錄下的另一個PY文件),另一類類類,只是延長計算器的行爲增加分而治之法。到目前爲止,它的工作原理,但suming時給我重複的結果,它是喜歡它認爲,該方案calcco.py的其餘部分是類計算器內。因此,這裏是我的代碼:重複的結果導入從另一個類文件PY

calcoo.py文件:

#! /usr/bin/python 
# -*- coding: utf-8 -*- 
import sys 
operator1= sys.argv[1] 
operation= sys.argv[2] 
operator2= sys.argv[3] 
try: 
    operator1 = float(sys.argv[1]) 
    operator2 = float(sys.argv[3]) 
except ValueError: 
    sys.exit("Error: Non numerical Parameters") 

class Calculator(): 

    def sumatory(self):         
     return float(operator1) + float(operator2) 
    def substract(self): 
     return float(operator1) - float(operator2) 

if operation == "sum": 
    print Calculator().sumatory() 
elif operation == "substract": 
    print Calculator().substract() 
else: 
    print "Error, operation not supported." 

calcoochild.py

#! /usr/bin/python 
# -*- coding: utf-8 -*- 
import sys 
operator1= sys.argv[1] 
operation= sys.argv[2] 
operator2= sys.argv[3] 
try: 
    operator1 = float(sys.argv[1]) 
    operator2 = float(sys.argv[3]) 
except ValueError: 
    sys.exit("Error: Non numerical Parameters") 
from calcoo import Calculator 
class CalculatorChild(Calculator): 
    def multiply(self):         
     return float(operator1) * float(operator2) 
    def divide(self): 
     if operator2 == 0: 
      print "Division by zero is not allowed." 
     else: 
      return float(operator1)/float(operator2) 

if operation == "sum": 
    print CalculatorChild().sumatory() 
elif operation == "substract": 
    print CalculatorChild().substract() 

elif operation == "multiply": 
    print CalculatorChild().multiply() 

elif operation == "divide": 
    print CalculatorChild().divide() 

else: 
    print "Error, operation not supported." 

當我執行calcoo.py一切正常,但是當我exectute蟒蛇calcoochild.py 3總和2.1例如它打印5.1兩次,如果我寫乘法打印:

Error, operation not supported 
6.3 

所以它就像CalculatorCHild繼承不僅方法sumatory和。減去,也exectues if子句,它的外部類,我試圖找到一個解決方案,但它不斷給我同樣的結果。我希望有人能幫助我,提前謝謝你。

回答

2

當您導入calcoo,全部代碼在頂層被執行。這包括解析sys.argv值。

移動運行模塊作爲腳本,由模塊名測試把守塊什麼時候應該只執行;如果名稱是__main__那麼你的代碼運行的腳本,否則就被導入爲模塊:

class Calculator(): 
    def sumatory(self):         
     return float(operator1) + float(operator2) 
    def substract(self): 
     return float(operator1) - float(operator2) 

if __name__ == '__main__': 
    import sys 
    operator1= sys.argv[1] 
    operation= sys.argv[2] 
    operator2= sys.argv[3] 
    try: 
     operator1 = float(sys.argv[1]) 
     operator2 = float(sys.argv[3]) 
    except ValueError: 
     sys.exit("Error: Non numerical Parameters") 

    if operation == "sum": 
     print Calculator().sumatory() 
    elif operation == "substract": 
     print Calculator().substract() 
    else: 
     print "Error, operation not supported." 

現在,當您導入calcoo只有Calculator類將被定義;其餘的代碼將不會運行。

+0

剛想回答了類似的回答 – justhalf

相關問題