用户输入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 *Thisisfile a
Thisisfile b>>>
解释:
from package_1 import *
导入package_1,加载所有的模块。首先会导入__init__.py,然后导入__all__变量中的模块。
在模糊导入时,形如from package import *,*是由__all__定义的。
为啥能在自定义模块内直接使用内置函数和内置常量?
这是内建模块builtins 的功劳
builtins模块, 内建对象。提供对Python的所有“内置”标识符的直接访问。
包括内置函数,如abs(),
内置常量,如copyright
>>> importbuiltins>>> 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__全局变量, 它指向。比如:
print("f1 and f2")
x= "a"
deff1():
x= 1
print('f1')def f2(*arg):print('f2')print(globals().keys())print(locals().keys())
运行它得到结果如下,可以看到"__builtins__"全局变量。
f1 andf2
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__"])#得到
使用
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.
还是上面的例子:👆
>>> importsys>>>sys.modules.keys()
dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_warnings', '_frozen_importlib_external',
'_io', 'marshal', 'posix', '_thread', '_weakref', 'time', 'zipimport', '_codecs', 'codecs',
'encodings.aliases', 'encodings', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1',
'_abc', 'abc', 'io', '_stat', 'stat', 'genericpath', 'posixpath', 'os.path', '_collections_abc',
'os', '_sitebuiltins', 'site', 'readline', 'atexit', 'rlcompleter','package_1', 'package_1.file_a', 'package_1.file_b'])
最后3个模块(标记黄色背景)就是被加载的自定义的模块。
当我们导入新modules,sys.modules将自动记录下该module;当第二次再导入该module时,Python将直接到字典中查找,加快运行速度。
sys.modules是一个dict,所以可以使用keys,values,items等方法。
2. namespace
也是dict格式。用于记录其内部的变量。
函数的命名空间:在它的命名空间内使用locals(),返回它的一个dict, 包括其内的所有对象信息。
模块的namespace: 在它的命名空间内使用locals()返回一个dict, 包括其内的所有对象信息,包括函数,变量,类,导入的模块。如果以脚本运行这个模块,那么直接使用globals()和locals()得到的是一样的。
程序访问一个变量,会通过命名空间逐一查找,顺序:
local namespace。注意,如果是在闭包内查找变量,没有的话,下一个查找目标是父函数的localnamespace。
global namespace
build-in namespace。
三 理解Python在执行import语句(导入内置(Python自个的)或第三方模块(已在sys.path中))