Python基础 Zero to Hero 理解__name__ 与 __main__

本文首发于伊洛的个人博客:https://yiluotalk.com,欢迎关注并查看更多内容!!!

1. 理解 __name__
  • 如果你经常看python的代码,很多脚本后面都会用到 if __name__ == '__main__':,对于刚接触python的小伙伴开始肯定会不大理解这是什么意思,为何这么使用。会纠结的理不清头绪,今天就这个痛点来简单的分解讲述下
  • __name__其实是python内置的系统变量,我们来首先来看看系统变量中有哪些内容
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

  • 很多内容直接找到__name__
  • 可见__name__就是内置的系统变量而已
2. 举个栗子
  • 来建个新的脚本
(yiluo) ➜  Code touch build.py
(yiluo) ➜  Code vim build.py
  • 脚本中写入
#!/usr/bin/env python3
# 伊洛Yiluo

print('__name__究竟是什么? ')
print('该脚本的 __name__值是:{}'.format(__name__))
  • 运行一下
(yiluo) ➜  Code python build.py
__name__究竟是什么?
该脚本的 __name__值是:__main__
  • 打印出的内容很清晰的说明当下脚本的__name__值是 __main__
  • 这就说明单独运行脚本的时候,__name__值就是是 __main__
3.作为模块导入时
  • Python 中一个.py 文件就是一个模块
(yiluo) ➜  Code python3
Python 3.7.5 (default, Nov 29 2019, 14:32:46)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import build
__name__究竟是什么?
该脚本的 __name__值是:build
  • __name__ 的值变成了 build
4.实际应用
  • 那么利用这点,我们如何实际应用,使导入代码的时候不被执行
#!/usr/bin/env python3
# 伊洛Yiluo

print('__name__究竟是什么? ')
print('该脚本的 __name__值是:{}'.format(__name__))


if __name__ == '__main__':
    print('我很倔强,我被导入的时候不会被打印!')
  • 来单独运行下build脚本
(yiluo) ➜  Code python build.py
__name__究竟是什么?
该脚本的 __name__值是:__main__
我很倔强,我被导入的时候不会被打印!
  • 看到最后的print打印了出来
  • 如果被导入呢?
(yiluo) ➜  Code python3
Python 3.7.5 (default, Nov 29 2019, 14:32:46)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import build
__name__究竟是什么?
该脚本的 __name__值是:build
  • __name__的值不是__main__的时候就不会打印出来了
  • 再新建一个其它的文件最后验证下
(yiluo) ➜  Code touch test.py
(yiluo) ➜  Code vim test.py
  • 键入代码
#!/usr/bin/env python3
# 伊洛Yiluo

import build
print('test脚本自己打印')
``
  • 命令行运行下
(yiluo) ➜  Code python test.py
__name__究竟是什么?
该脚本的 __name__值是:build
test脚本自己打印
  • 可见并没有打印出“我很倔强,我被导入的时候不会被打印!”
5. 总结
  • 当脚本下面if __name__ == "__main__":码入代码时,被导入到其它脚本中的时候不会被执
    在这里插入图片描述

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
2019年12月18日
愿您享受每一天,Just Enjoy !

关注公众号获取更多内容

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值