简体   繁体   English

为什么这个Python代码执行两次?

[英]Why is this Python code executing twice?

I'm very new to Python and trying to learn how classes, methods, scopes, etc works by building very silly programs with no real purpose. 我是Python的新手,试图通过构建非常愚蠢的程序来学习类,方法,范围等是如何工作的。

The code I wrote below is suppose to just define a class Functions that is instantiated using an x and a y value and then one can execute various simple math functions like add subtract, multiply or divide (yes I know there is a Python Math library). 我下面写的代码是假设只是定义一个类Functions正在使用实例化的xy值,那么就可以执行各种简单的数学功能,如加,减,乘或除(是的,我知道有一个Python的数学库) 。

However, whenever I run my code and I get to the section where I want to run a math function in my class it runs the entire program over again and then does the math function. 但是,每当我运行我的代码并进入我想要在我的类中运行数学函数的部分时,它会再次运行整个程序,然后执行数学运算。

What am I doing wrong here? 我在这做错了什么?

The file name is MyMath.py 文件名是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())

Remove the following statement. 删除以下语句。

from MyMath import Functions

The first line of the program defines the name Functions , and you can use it without having to import it. 程序的第一行定义名称Functions ,您可以使用它而无需导入它。 You only use the import command if the class (or function, or variable, ...) is defined in a different file/module. 如果在不同的文件/模块中定义了类(或函数或变量,...),则只使用import命令。

Note in addition: When you import anything from a module the whole module is run as a script (although only the Functions name is imported into the local namespace). 另请注意:从模块导入任何内容时,整个模块作为脚本运行(尽管只将Functions名称导入到本地名称空间)。 For this reason, everything within a file to be imported should be contained inside a class or function (unless there is a good reason not to...). 因此,要导入的文件中的所有内容都应包含在类或函数中(除非有充分的理由不...)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM