理解python的主要方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22492162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:02:59  来源:igfitidea点击:

Understanding the main method of python

pythonpython-3.x

提问by Erran Morad

I am new to Python, but I have experience in other OOP languages. My course does not explain the main method in python.

我是 Python 新手,但我有其他 OOP 语言的经验。我的课程没有解释python中的主要方法。

Please tell me how main method works in python ? I am confused because I am trying to compare it to Java.

请告诉我主要方法在 python 中是如何工作的?我很困惑,因为我试图将它与 Java 进行比较。

def main():
# display some lines

if __name__ == "__main__": main()

How is main executed and why do I need this strange ifto execute main. My code is terminated without output when I remove the if.

main 是如何执行的,为什么我需要这个奇怪的if来执行main。当我删除if.

The minimal code -

最小的代码 -

class AnimalActions:
    def quack(self): return self.strings['quack']
    def bark(self): return self.strings['bark']

class Duck(AnimalActions):
    strings = dict(
        quack = "Quaaaaak!",
        bark = "The duck cannot bark.",
    )


class Dog(AnimalActions):
    strings = dict(
        quack = "The dog cannot quack.",
        bark = "Arf!",
    )

def in_the_doghouse(dog):
    print(dog.bark())

def in_the_forest(duck):
    print(duck.quack())

def main():
    donald = Duck()
    fido = Dog()

    print("- In the forest:")
    for o in ( donald, fido ):
        in_the_forest(o)

    print("- In the doghouse:")
    for o in ( donald, fido ):
        in_the_doghouse(o)

if __name__ == "__main__": main()

采纳答案by Jim Dennis

The Python approach to "main" is almost unique to the language(*).

Python 的“main”方法几乎是该语言所独有的(*)。

The semantics are a bit subtle. The __name__identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__is set to "__main__"(the literal string: __main__).

语义有点微妙。的__name__,因为它是被导入标识绑定到任何模块的名称。但是,当文件正在执行时,则__name__设置为"__main__"(文字字符串:)__main__

This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:

这几乎总是用于将应该执行的代码部分与定义功能的代码部分分开。所以 Python 代码通常包含如下一行:

#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
    pass

def some_function(*args,**kwargs):
    pass

if __name__ == '__main__':
    print("This only executes when %s is executed rather than imported" % __file__)

Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.

使用这一约定,可以让文件定义在其他程序中使用的类和函数,并且还包括仅在文件作为独立脚本被调用时进行评估的代码。

It's important to understand that all of the code above the if __name__line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a printstatement before the if __name__line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).

重要的是要了解if __name__在这两种情况下,该行上方的所有代码都正在执行、评估。当文件被导入或执行时,解释器会对其进行评估。如果您print在该if __name__行之前放置一个语句,那么每次任何其他代码尝试将其作为模块导入时,它都会打印输出。(当然,这将是反社会的。不要那样做)。

I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.

我个人喜欢这些语义。它鼓励程序员将功能(定义)与功能(执行)分开并鼓励重用。

Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__"to isolate a block of code which calls a suite of unit tests that apply to this module.

理想情况下,如果从命令行调用,几乎每个 Python 模块都可以做一些有用的事情。在许多情况下,这用于管理单元测试。如果特定文件定义了仅在系统其他组件的上下文中有用的功能,那么仍然可以使用__name__ == "__main__"隔离调用适用于该模块的一组单元测试的代码块。

(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).

(如果您不打算使用任何此类功能或单元测试,那么最好确保文件模式不可执行)。

Summary: if __name__ == '__main__':has two primary use cases:

总结:if __name__ == '__main__':有两个主要用例:

  • Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)
  • Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.
  • 允许模块提供导入其他代码的功能,同时还提供有用的语义作为独立脚本(围绕功能的命令行包装器)
  • 允许模块定义一组单元测试,这些单元测试与要测试的代码一起存储(在同一文件中),并且可以独立于代码库的其余部分执行。

It's fairly common to def main(*args)and have if __name__ == '__main__':simply call main(*sys.argv[1:])if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module()and calling test_module()in your if __name__ == '__main__:'suite.

如果您想以类似于其他一些编程语言的方式定义 main ,那么它很常见def main(*args)并且if __name__ == '__main__':只需调用即可main(*sys.argv[1:])。如果您的 .py 文件主要用作其他代码中的模块,那么您可能会在您的套件中def test_module()调用。test_module()if __name__ == '__main__:'

  • (Ruby also implements a similar feature if __file__ == $0).
  • (Ruby 也实现了类似的功能if __file__ == $0)。

回答by Aaron

If you import the module (.py) file you are creating now from another python script it will notexecute the code within

如果您从另一个 python 脚本导入您现在创建的模块 (.py) 文件,它将不会执行其中的代码

if __name__ == '__main__':
    ...

If you run the script directly from the console, it will be executed.

如果直接从控制台运行脚本,它将被执行。

Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution orimporting of the module.

Python 不使用或不需要 main() 函数。任何不受该保护保护的代码都将在执行导入模块时执行。

This is expanded upon a little more at python.berkely.edu

这在python.berkely.edu上有更多扩展

回答by Code-Apprentice

Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The ifstatement allows you to create a mainfunction which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

Python 没有像 Java、C、C++ 等那样定义的入口点。它只是逐行执行源文件。该if语句允许您创建一个main函数,如果您的文件作为“主”模块而不是另一个模块中的库加载,则该函数将被执行。

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar:and def foobar()creates either a class or a function and stores them in memory for later use.

明确地说,这意味着 Python 解释器从文件的第一行开始并执行它。执行类似class Foobar:def foobar()创建类或函数的行并将它们存储在内存中以备后用。

回答by Erran Morad

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

在 Python 中,执行不必从 main 开始。首先执行“可执行代码”的第一行。

def main():
    print("main code")

def meth1():
    print("meth1")

meth1()
if __name__ == "__main__":main() ## with if

Output -

输出 -

meth1
main code

More on main() -http://ibiblio.org/g2swap/byteofpython/read/module-name.html

更多关于 main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html

A module's __name__

一个模块的 __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the nameattribute of the module.

每个模块都有一个名称,模块中的语句可以找到其模块的名称。这在特定情况下特别方便 - 如前所述,当第一次导入模块时,会运行该模块中的主块。如果我们只想在程序被自己使用而不是从另一个模块导入时运行块怎么办?这可以使用模块的name属性来实现。

Using a module's __name__

使用模块的 __name__

#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Output -

输出 -

$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

How It Works -

这个怎么运作 -

Every Python module has it's __name__defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

每个 Python 模块都有它的__name__定义,如果是__main__,则意味着该模块由用户独立运行,我们可以执行相应的适当操作。