为什么此Python代码执行两次? [英] Why is this Python code executing twice?

查看:97
本文介绍了为什么此Python代码执行两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,它试图通过构建没有目的的非常愚蠢的程序来学习类,方法,范围等的工作原理.

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.

我在下面编写的代码假设只定义了一个 Functions 类,该类使用 x y 值实例化,然后使用可以执行各种简单的数学函数,例如加减,乘或除(是的,我知道有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).

但是,每当我运行代码并到达要在班级中运行数学函数的部分时,它将再次运行整个程序,然后执行数学函数.

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.

我在做什么错了?

文件名为 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())

推荐答案

删除以下语句.

from MyMath import Functions

程序的第一行定义名称 Functions ,您可以使用它而不必导入它.仅当在不同的文件/模块中定义了类(或函数,变量,...)时,才使用import命令.

The first line of the program defines the name Functions, and you can use it without having to import it. You only use the import command if the class (or function, or variable, ...) is defined in a different file/module.

另外请注意::从模块导入任何内容时,整个模块都将作为脚本运行(尽管只有 Functions 名称会导入到本地名称空间中).因此,要导入的文件中的所有内容都应包含在类或函数中(除非有充分的理由不这样做).

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). 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...).

这篇关于为什么此Python代码执行两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆