用户输入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.

还是上面的例子:

python : import详解。的更多相关文章

  1. Python Import 详解

    http://blog.csdn.net/appleheshuang/article/details/7602499 一 module通常模块为一个文件,直接使用import来导入就好了.可以作为mo ...

  2. python import详解

    1.import作用 引入模块 2.import的特点 一个程序中,import的模块不会重复被引用,如: # test1.py import test2 print test2.attr # tes ...

  3. Python闭包详解

    Python闭包详解 1 快速预览 以下是一段简单的闭包代码示例: def foo(): m=3 n=5 def bar(): a=4 return m+n+a return bar >> ...

  4. [转] Python Traceback详解

    追莫名其妙的bugs利器-mark- 转自:https://www.jianshu.com/p/a8cb5375171a   Python Traceback详解   刚接触Python的时候,简单的 ...

  5. python 数据类型详解

    python数据类型详解 参考网址:http://www.cnblogs.com/linjiqin/p/3608541.html 目录1.字符串2.布尔类型3.整数4.浮点数5.数字6.列表7.元组8 ...

  6. python线程详解

    #线程状态 #线程同步(锁)#多线程的优势在于可以同时运行多个任务,至少感觉起来是这样,但是当线程需要共享数据时,可能存在数据不同步的问题. #threading模块#常用方法:'''threadin ...

  7. python数据类型详解(全面)

    python数据类型详解 目录1.字符串2.布尔类型3.整数4.浮点数5.数字6.列表7.元组8.字典9.日期 1.字符串1.1.如何在Python中使用字符串a.使用单引号(')用单引号括起来表示字 ...

  8. Python Collections详解

    Python Collections详解 collections模块在内置数据结构(list.tuple.dict.set)的基础上,提供了几个额外的数据结构:ChainMap.Counter.deq ...

  9. 转 python数据类型详解

    python数据类型详解 目录 1.字符串 2.布尔类型 3.整数 4.浮点数 5.数字 6.列表 7.元组 8.字典 9.日期 1.字符串 1.1.如何在Python中使用字符串 a.使用单引号(' ...

随机推荐

  1. TensorFlow.ZC尝试

    1.资料: https://github.com/protocolbuffers/protobuf/releases https://pythonprogramming.net/introductio ...

  2. golang 二维切片

    初始化: res := make([][length]int, length), 例如: res := make([][2]int, 10) fmt.Println(res) 输出: [[0 0] [ ...

  3. 石子合并/能量项链【区间dp】

    题目链接:http://www.51mxd.cn/problem.php-pid=737.htm 题目大意:给出n个石子堆以及这n个石子堆中石子数目,每次操作合并两个相邻的石子堆,代价为两个石子堆数目 ...

  4. Shell脚本之流程控制(if、for、while)

    if 判断 if语句的三种格式: (1)if (2)if else (3)if elif else 语法格式如下: #if 语法格式 if 条件 then 命令1... 命令2... fi #if e ...

  5. HDU 4578 线段树玄学算法?

    Transformation 题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=4578 Problem Description Yuanfang is p ...

  6. NOIP 2018 提高组初赛试题 题目+答案+简要解析

    一.单项选择题(共 10  题,每题 2  分,共计 20  分: 每题有且仅有一个正确选项)       1. 下列四个不同进制的数中,与其它三项数值上不相等的是( ). A. (269) 16 B ...

  7. 记笔记的软件(vnote)

    前面我们已经把我们的 Ubuntu 系统在物理机上运行起来了,也做了一些简单的优化,教了大家怎么使用 Ubuntu 系统自带的应用商店和 apt 安装和卸载软件.接着我们安装了搜狗输入法,现在我们的系 ...

  8. 怎样删除一条Cookie

    删除Cookie的唯一方法是: 将Expires设置为一个过去值, 一般会设置为 Thu, 01-Jan-1970 00:00:01 GMT 因为这是时间零点, 设这个总不会错. document.c ...

  9. Python实现乘法表——在列表里进行for循环设初值

    代码:最大的收获是二维列表的实现:[0]*9结果是[0,0,0,0,0,0,0,0,0,0],再加上for i in range(9),代表是9行[0,0,0,0,0,0,0,0,0,0],也就是9* ...

  10. dev gridview 单元格值拖拽替换

    public class GridViewDropCell { //dvginfo根据鼠标点击的x.y坐标获取该点的相关信息 private GridHitInfo downHitInfo; priv ...