python : import详解。
用户输入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详解。的更多相关文章
- Python Import 详解
http://blog.csdn.net/appleheshuang/article/details/7602499 一 module通常模块为一个文件,直接使用import来导入就好了.可以作为mo ...
- python import详解
1.import作用 引入模块 2.import的特点 一个程序中,import的模块不会重复被引用,如: # test1.py import test2 print test2.attr # tes ...
- Python闭包详解
Python闭包详解 1 快速预览 以下是一段简单的闭包代码示例: def foo(): m=3 n=5 def bar(): a=4 return m+n+a return bar >> ...
- [转] Python Traceback详解
追莫名其妙的bugs利器-mark- 转自:https://www.jianshu.com/p/a8cb5375171a Python Traceback详解 刚接触Python的时候,简单的 ...
- python 数据类型详解
python数据类型详解 参考网址:http://www.cnblogs.com/linjiqin/p/3608541.html 目录1.字符串2.布尔类型3.整数4.浮点数5.数字6.列表7.元组8 ...
- python线程详解
#线程状态 #线程同步(锁)#多线程的优势在于可以同时运行多个任务,至少感觉起来是这样,但是当线程需要共享数据时,可能存在数据不同步的问题. #threading模块#常用方法:'''threadin ...
- python数据类型详解(全面)
python数据类型详解 目录1.字符串2.布尔类型3.整数4.浮点数5.数字6.列表7.元组8.字典9.日期 1.字符串1.1.如何在Python中使用字符串a.使用单引号(')用单引号括起来表示字 ...
- Python Collections详解
Python Collections详解 collections模块在内置数据结构(list.tuple.dict.set)的基础上,提供了几个额外的数据结构:ChainMap.Counter.deq ...
- 转 python数据类型详解
python数据类型详解 目录 1.字符串 2.布尔类型 3.整数 4.浮点数 5.数字 6.列表 7.元组 8.字典 9.日期 1.字符串 1.1.如何在Python中使用字符串 a.使用单引号(' ...
随机推荐
- 02.03 win server r2 搭建FTP站点
============ftp服务器搭建=============== 先要搭建iis信息服务: 1.打开服务器管理器,角色>添加角色 2.选择角色服务:应用程序开发.FTP服务器.安全性 3. ...
- 数据库连接池——C3P0&Druid(快速入门)
数据库连接池--C3P0&Druid (一) 数据库连接池 每一个事物都有其存在的意义,在初学jdbc的时候,我们建立数据库连接对象后,会对其进行释放,但是数据库连接的建立和关闭是非常消耗资源 ...
- Docker daemon.json 的配置项目合集
这几天看了一点docker相关的东西, 在学习中: 看了下园友的blog 感觉很好 这里 学习一下. https://www.cnblogs.com/pzk7788/p/10180197.html 其 ...
- 利用js对象将iframe数据缓存, 实现子页面跳转后, 返回时不丢失之前填写的数据
利用js对象将iframe数据缓存, 实现子页面跳转后, 返回时不丢失之前填写的数据 实现描述:将数据存放在js对象中, 然后放在父页面的document对象中, 在页面刷新的时候将父页面的值取出来, ...
- 【IDEA插件】—— 代码量统计工具Statistic
1.下载 1.打开idea设置界面,选择 plugins标签 2.搜索“Statistic”插件,点击 install 3.重启IDEA 2.使用 1.菜单栏中找到view 2.在下层目录中找到Sta ...
- dede按照权重排序dede:list和得的:arclist
dede:list 的方法 1.找到"根目录\include\arc.listview.class.php"文件. 2.修改代码:在文件第727行处添加按weight排序判断代码( ...
- 测试常用__linux命令
1.显示目录和文件的命令 Ls:用于查看所有文件夹的命令. Dir:用于显示指定文件夹和目录的命令 Tree: 以树状图列出目录内容 Du:显示目录或文件大小 2.修改目录,文件权限和属主及数组命令 ...
- 指针生成网络(Pointer-Generator-Network)原理与实战
指针生成网络(Pointer-Generator-Network)原理与实战 阅读目录 0 前言 1 Baseline sequence-to-sequence 2 Pointer-Generat ...
- poj 1006中国剩余定理模板
中国剩余定理(CRT)的表述如下 设正整数两两互素,则同余方程组 有整数解.并且在模下的解是唯一的,解为 其中,而为模的逆元. 模板: int crt(int a[],int m[],int n) { ...
- centos中拉取postgre
新搭建好的linux服务器环境,docker也配置好了. 第一步,下载postgre docker pull postgres:11 这里的版本号自己按照自己的需要来获取. 然而实际上没那么顺利,直接 ...