简体   繁体   English

为什么 __name__ 等于 __main__?

[英]why __name__ is equal to __main__?

I understand that __main__ is the name of __main__.py , which in this case is test_employee .我知道__main____main__.py的名称,在这种情况下是test_employee But what I don't understand is the unittest module and the class that I want to test are being imported.但我不明白的是 unittest 模块和我要测试的 class 正在导入。 Then why __name__ is still same as __main__ ?那么为什么__name__仍然与__main__相同? As I understood, __name__ represents the modules being imported.据我了解, __name__代表正在导入的模块。

test_employee.py test_employee.py

import unittest

from employee import Employee

class TestEmployee(unittest.TestCase):

    def setUp(self):
        self.employee1 = Employee('June', 'July')
        self.employee2 = Employee('Jane', 'Marshal')
    
    def test_give_default_raise(self):
        self.assertEqual(5000, self.employee1.annual_salary)

    def test_give_custom_raise(self):
        self.employee2.give_raise(1000)
        self.assertEqual(6000, self.employee2.annual_salary)

if __name__ == '__main__':
    unittest.main()

__main__ is a very particular function of python. __main__是 python 的一个非常特殊的 function。 It has mainly two interests:它主要有两个兴趣:

  • if __name__ == '__main__' condition if __name__ == '__main__'条件
  • __main__.py file for a module (which is not the purpose hier)模块的__main__.py文件(这不是目的层)

When importing a module, the __name__ attribute of this module is set to the name of the module (ie the file name without the.py extension).导入模块时,将该模块的__name__属性设置为模块的名称(即不带.py 扩展名的文件名)。

>>> import my_module
>>> my_module.__name__
'my_module'

>>> import my_module.submodule
>>> my_module.submodule.__name__
'my_module.submodule'

However, if the attribute is called from the main runtime environment (which is the main use case), then the variable will always contain the value '__main__' .但是,如果从主运行时环境(这是主要用例)调用该属性,则该变量将始终包含值'__main__' The main purpose of this is to test whether the main script is called from the main runtime environment or not.这样做的主要目的是测试是否从主运行时环境调用主脚本。 This is usefull to differentiate the case where the module is called directly (for instance from command line) and the one where it is loaded from another module (to launch an argparse, for example...)这有助于区分直接调用模块的情况(例如从命令行)和从另一个模块加载模块的情况(例如,启动 argparse...)

Nevertheless, it is recommended to put as little code as possible under the condition if __name__ == '__main__' to avoid errors.尽管如此,还是建议在if __name__ == '__main__'条件下尽量少放代码以避免错误。

It is recommended to do as follows:建议执行以下操作:

# echo.py

import shlex
import sys

def echo(phrase: str) -> None:
   """A dummy wrapper around print."""
   # for demonstration purposes, you can imagine that there is some
   # valuable and reusable logic inside this function
   print(phrase)

def main() -> int:
    """Echo the input arguments to standard output"""
    phrase = shlex.join(sys.argv)
    echo(phrase)
    return 0

if __name__ == '__main__':
    sys.exit(main())

Functions and classes that are defined, but none of their code runs.已定义但没有代码运行的函数和类。 When You Use name == main its Executed when invoked directly as when its invoked directly name will be main.当您使用name == main时,它在直接调用时执行,因为它直接调用时name将是 main。

You are running the test inside main module..not the Employee(which is being imported)..so when you setUp the unittest, the instance of Employee becomes the instant of TestEmployee class..Hope it was clear to you!!!您正在主模块内运行测试..而不是 Employee(正在导入)..所以当您设置单元测试时,Employee 的实例成为 TestEmployee class 的瞬间..希望你清楚!

When you run your script, the __name__ variable equals __main__ .运行脚本时, __name__变量等于__main__ When you import a script, __name__ will contain the name of the script.导入脚本时, __name__将包含脚本的名称。

So when you run test_employee.py :因此,当您运行test_employee.py时:

  • __name__ in test_employee.py will be __main__ __name__中的 __name__ 将是__main__
  • __name__ in employee.py will be employee employee.py 中的__name__将是employee
  • __name__ in unittest.py will be unittest unittest.py 中的__name__将是unittest

For more information you can have a look here: https://www.freecodecamp.org/news/whats-in-a-python-s-name-506262fe61e8/有关更多信息,您可以在这里查看: https://www.freecodecamp.org/news/whats-in-a-python-s-name-506262fe61e8/

The __name__ and __main__ has been very well described in below Python documentation: __name____main__在下面的 Python 文档中有很好的描述:

https://docs.python.org/3/library/__main__.html#:~:text=%C2%B6,entry%20point%20to%20the%20application . https://docs.python.org/3/library/__main__.html#:~:text=%C2%B6,entry%20point%20to%20the%20application

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

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