理解python的主要方法 [英] Understanding the main method of python

查看:42
本文介绍了理解python的主要方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

def main():
# display some lines

if __name__ == "__main__": main()

main 是如何执行的,为什么我需要这个奇怪的 if 来执行 main.当我删除 if 时,我的代码在没有输出的情况下终止.

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

最小的代码 -

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

推荐答案

Python 的main"方法几乎是该语言独有的(*).

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

语义有点微妙.__name__ 标识符在导入时绑定到任何模块的名称.但是,当文件正在执行时,__name__ 被设置为 "__main__"(文字字符串:__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__).

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

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:

#!/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.

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

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

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

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

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

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.

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

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

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

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

  • 允许模块提供导入其他代码的功能,同时还提供有用的语义作为独立脚本(围绕功能的命令行包装器)
  • 允许模块定义一组单元测试,这些单元测试与要测试的代码一起存储(在同一文件中),并且可以独立于代码库的其余部分执行.

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

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.

  • (Ruby 也实现了类似的功能 if __file__ == $0).

这篇关于理解python的主要方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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