用户输入input()

input()函数: 用于从标准输入读取数值。

>>> message = input('tell me :')
tell me :hahah
>>> message
'hahah'

相关:

Unix的内建命令read的功能和Python的input()类似。都是重标准输入读取数值。只不过,input函数丰富了功能,可以直接加上提示参数。


import知识

一 什么是pcakage包和module?

模块 module:以.py为后缀的文件。也包括”.pyo”、”.pyc”、”.pyd”、”.so”、”.dll”。

包 package: 为避免模块名冲突,Python引入了按目录组织模块的方法,称之为包。

包文件夹内,有一个__init__.py文件,作为证明这是一个包的标志。这个文件可以为空。

例子:

⮀ cd package_1
/package_1 ⮀ touch __init__.py
/package_1 ⮀ ls
__init__.py
/package_1 ⮀ touch file_a.py
/package_1 ⮀ touch file_b.py #在__init__.py中加上:
#__all__ = ['file_a.py', 'file_b.py']
#file_a.py
print('this is file_a')
#file_b.py
print('this is file_b')
python练习 ⮀ python3>>> from package_1 import *
This is file a
This is file b
>>>

解释:

from package_1 import *

导入package_1,加载所有的模块。首先会导入__init__.py,然后导入__all__变量中的模块。

在模糊导入时,形如from package import *,*是由__all__定义的。

为啥能在自定义模块内直接使用内置函数和内置常量?

这是内建模块builtins 的功劳

builtins模块,  内建对象。提供对Python的所有“内置”标识符的直接访问。

  • 包括内置函数,如abs(),
  • 内置常量,如copyright
>>> import builtins
>>> builtins.__dict__.keys()
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__build_class__', '__import__', 'abs', 'all', 'any', 'ascii', 'bin', 'breakpoint', 'callable', 'chr', 'compile', 'delattr', 'dir', 'divmod', 'eval', 'exec', 'format', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'isinstance', 'issubclass', 'iter', 'len', 'locals', 'max', 'min', 'next', 'oct', 'ord', 'pow', 'print', 'repr', 'round', 'setattr', 'sorted', 'sum', 'vars', 'None', 'Ellipsis', 'NotImplemented', 'False', 'True', 'bool', 'memoryview', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'enumerate', 'filter', 'float', 'frozenset', 'property', 'int', 'list', 'map', 'object', 'range', 'reversed', 'set', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'type', 'zip', '__debug__', 'BaseException', 'Exception', 'TypeError', 'StopAsyncIteration', 'StopIteration', 'GeneratorExit', 'SystemExit', 'KeyboardInterrupt', 'ImportError', 'ModuleNotFoundError', 'OSError', 'EnvironmentError', 'IOError', 'EOFError', 'RuntimeError', 'RecursionError', 'NotImplementedError', 'NameError', 'UnboundLocalError', 'AttributeError', 'SyntaxError', 'IndentationError', 'TabError', 'LookupError', 'IndexError', 'KeyError', 'ValueError', 'UnicodeError', 'UnicodeEncodeError', 'UnicodeDecodeError', 'UnicodeTranslateError', 'AssertionError', 'ArithmeticError', 'FloatingPointError', 'OverflowError', 'ZeroDivisionError', 'SystemError', 'ReferenceError', 'MemoryError', 'BufferError', 'Warning', 'UserWarning', 'DeprecationWarning', 'PendingDeprecationWarning', 'SyntaxWarning', 'RuntimeWarning', 'FutureWarning', 'ImportWarning', 'UnicodeWarning', 'BytesWarning', 'ResourceWarning', 'ConnectionError', 'BlockingIOError', 'BrokenPipeError', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionRefusedError', 'ConnectionResetError', 'FileExistsError', 'FileNotFoundError', 'IsADirectoryError', 'NotADirectoryError', 'InterruptedError', 'PermissionError', 'ProcessLookupError', 'TimeoutError', 'open', 'quit', 'exit', 'copyright', 'credits', 'license', 'help', '_'])

原理:

大多数模块中都有__builtins__全局变量, 它指向<module 'builtins' (built-in)>。比如:

print("f1 and f2")
x = "a" def f1():
x = 1
print('f1') def f2(*arg):
print('f2') print(globals().keys()) print(locals().keys())

运行它得到结果如下,可以看到"__builtins__"全局变量。

f1 and f2
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'x', 'f1', 'f2'])
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'x', 'f1', 'f2'])
#如果运行:
print(locals()["__builtins__"])
#得到<module 'builtins' (built-in)>

使用

print(locals()["__builtins__"].copyright)
#等同于,直接使用内置常量:
copyright

由此可知通过全局变量__builtins__,可以在这个自定义的模块直接使用内置函数或内置常量。

二 解释sys.modules, namespace, built-in property

1.sys.modules(定义)

This is a dictionary that maps module names to modules which have already been loaded.

还是上面的例子:

最新文章

  1. Java开发实践 集合框架 全面分析
  2. visual studio 的Error List 显示乱码
  3. iOS之 APNs全新的APNs苹果15年WWDC大会上的干货
  4. java,我准备好了
  5. 实现公告栏无缝滚动的js代码(转)
  6. bjfu1262 优先队列
  7. js技巧总结
  8. sql 选取每个分组中的第一条数据
  9. ant中调用外部ant任务的两种方法
  10. ci 中使用 pdo 连接 mysql
  11. hdu 2955 Robberies 背包DP
  12. Redmine开启服务
  13. SERVICE_USE_PID
  14. HDU 4787 GRE Words Revenge
  15. Go 实现 NumberFormat 函数
  16. LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation]
  17. C#字符串的CompareTo比较,让我疑惑的地方
  18. Codeforces Round #539 (Div. 2) 异或 + dp
  19. airflow 实战
  20. CSS的再深入(更新中&#183;&#183;&#183;)

热门文章

  1. 【ARM-Linux开发】Linux下更改目录下所有文件的所有者及其权限
  2. php display_errors
  3. matplotlib画图总结--多子图布局
  4. last 和 lastb 命令
  5. WebForm——浅拷贝与深拷贝
  6. Windows 与 linux文件相互传输的方法
  7. operator模块和functools模块
  8. layui upload 在JS动态加载内容后, 点击按钮无反应
  9. element-ui 中 table 鼠标悬停时背景颜色修改
  10. zepto学习(三)之详解