用户输入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. 不同Json工具对空串和NULL的序列号处理:net.sf.json 和 fastjson

    目录 1.测试代码 2.测试结果: 3.总结: 4.注:Maven中引入net.sf.json的方式 net.sf.json 和 fastjson 对于空串和NULL的处理: 1.测试代码 packa ...

  2. JavaSE基础(八)--Java 循环结构

    Java 循环结构 - for, while 及 do...while 顺序结构的程序语句只能被执行一次.如果您想要同样的操作执行多次,,就需要使用循环结构. Java中有三种主要的循环结构: whi ...

  3. poj3449(判断直线相交)

    题目链接:https://vjudge.net/problem/POJ-3449 题意:给出若干几何体,判断每个几何体与其它几何体的相交情况,并依次输出. 思路: 首先要知道的是根据正方形对角线的两个 ...

  4. django fields lookup methods(lookup类型)

    __exact        精确等于 like 'aaa' __iexact    精确等于 忽略大小写 ilike 'aaa' __contains    包含 like '%aaa%' __ic ...

  5. url-pattern / 与/* 的区别

    其中/和/*的区别:< url-pattern>/</url-pattern> 会匹配到/login这样的路径型url 不会匹配到模式为*.jsp这样的后缀型url,即:*.j ...

  6. Mac终端 bash和zsh切换方法

    切换到bash chsh -s /bin/bash 切换到zsh chsh -s /bin/zsh 终端重启后生效

  7. SpringCloud 教程 | 终章

    错过了这一篇,你可能再也学不会 Spring Cloud 了!Spring Boot做为下一代 web 框架,Spring Cloud 作为最新最火的微服务的翘楚,你还有什么理由拒绝.赶快上船吧,老船 ...

  8. ffmpeg AVPacket结构体及其相关函数

    0. 简介 AVPacket结构体并不是很复杂, 但是在ffmpeg中用的非常多. 与其相关的函数也是比较多. AVPacket保存了解复用之后, 解码之前的数据, 和这些数据相关的一些附加信息. 对 ...

  9. FastAdmin

    FastAdmin是一款基于ThinkPHP5+Bootstrap的极速后台开发框架. 感觉挺好用的. 开发文档https://doc.fastadmin.net/docs/index.html 根据 ...

  10. 火狐 , IE , 谷歌浏览器的 驱动下载地址汇总

    一.Firefox和驱动下载地址 所有火狐浏览器版本下载地址:http://ftp.mozilla.org/pub/firefox/releases/ 所有火狐驱动geckodriver版本下载地址: ...