python : import详解。
2024-09-05 05:48:25
用户输入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.
还是上面的例子:
最新文章
- Java开发实践 集合框架 全面分析
- visual studio 的Error List 显示乱码
- iOS之 APNs全新的APNs苹果15年WWDC大会上的干货
- java,我准备好了
- 实现公告栏无缝滚动的js代码(转)
- bjfu1262 优先队列
- js技巧总结
- sql 选取每个分组中的第一条数据
- ant中调用外部ant任务的两种方法
- ci 中使用 pdo 连接 mysql
- hdu 2955 Robberies 背包DP
- Redmine开启服务
- SERVICE_USE_PID
- HDU 4787 GRE Words Revenge
- Go 实现 NumberFormat 函数
- LeetCode 31 Next Permutation / 60 Permutation Sequence [Permutation]
- C#字符串的CompareTo比较,让我疑惑的地方
- Codeforces Round #539 (Div. 2) 异或 + dp
- airflow 实战
- CSS的再深入(更新中&#183;&#183;&#183;)