[英]Duplicated results when importing methods from a class of another py file
我是python的新手,所以我希望你可以帮我解决这个愚蠢的问题,因为我找不到任何理由让这个问题发生。 所以,我有一个名为calcoo.py的文件,它有一个名为Calculator的类,可以求和减,然后我在另一个名为CalculatorCHild的类中继承该类(位于同一目录的另一个py文件中),只是扩展了Calculator的行为添加除法和乘法。 到目前为止它的工作原理但在总结时给出了重复的结果,它就像它认为程序的其余部分calcco.py在类Calculator中。 所以这是我的代码:
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时一切正常,但是当我执行python calcoochild.py 3 sum 2.1例如它打印5.1两次,如果我写multips它打印:
Error, operation not supported
6.3
所以它就像CalculatorCHild不仅继承了sumatory和substract这样的方法,而且它还可以解释它在类之外的if子句,我试图找到一个解决方案,但它一直给我相同的结果。 我希望有人可以帮助我,提前谢谢你。
导入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
类; 其余的代码将不会运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.