hax*_*ode 3 python functional-programming
我是Python的新手,试图通过构建非常愚蠢的程序来学习类,方法,范围等是如何工作的.
我在下面编写的代码假设只是定义一个Functions使用a x和yvalue 实例化的类,然后可以执行各种简单的数学函数,如add subtract,multiply或divide(是的,我知道有一个Python Math库).
但是,每当我运行我的代码并进入我想要在我的类中运行数学函数的部分时,它会再次运行整个程序,然后执行数学运算.
我在这做错了什么?
文件名是MyMath.py
class Functions():
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
return self.x+self.y
def subtract(self):
return self.x-self.y
def multiply(self):
return self.x*self.y
def divide(self):
return self.x/self.y
def check_input(input):
if input == int:
pass
else:
while not input.isdigit():
input = raw_input("\n " + input + " is not a number. Please try again: ")
return input
print("Welcome to the customzied Math program!")
x = raw_input("\nTo begin, please enter your first number: ")
x = check_input(x)
y = raw_input("Enter your second number: ")
y = check_input(y)
from MyMath import Functions
math = Functions(x,y)
print(math.add())
Run Code Online (Sandbox Code Playgroud)
删除以下语句.
from MyMath import Functions
Run Code Online (Sandbox Code Playgroud)
程序的第一行定义名称Functions,您可以使用它而无需导入它.如果在不同的文件/模块中定义了类(或函数或变量,...),则只使用import命令.
另请注意:从模块导入任何内容时,整个模块作为脚本运行(尽管只将Functions名称导入本地名称空间).因此,要导入的文件中的所有内容都应包含在类或函数中(除非有充分的理由不...).
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |