builtins内建模块

builtins模块

为啥我们没有导入任何模块就能使用len(),str(),print()...等这么多的函数?

其实在我们运行python解释器的时候,他会自动导入一些模块,这些函数就是从这些地方来的,这些函数被称为内建函数

首先查看执行文件的名称空间有些啥

首先在最后面是我们自己编写的内容,zx和x,那么前面一堆是些啥呢

class zx():
    name="zx"
xxxx=1
print(dir())
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'xxxx', 'zx']

打印一下吧

我们发现,这些属性只有一个是模块对象

class zx():
    name="zx"
xxxx=1
print(dir())

print(__annotations__)
print(__builtins__)
print(__cached__)
print(__doc__)
print(__file__)
print(__loader__)
print(__name__)
print(__package__)
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'xxxx', 'zx']
{}
<module 'builtins' (built-in)>
None
None
C:/Users/Administrator/Desktop/01python/研究/自带self查找/fgdf.py
<_frozen_importlib_external.SourceFileLoader object at 0x00000258B107E9B0>
__main__
None

看下这个模块到底放了些啥

我们惊讶的发现,原来我们日常使用的一些函数原来都藏在这里,

class zx():
    name="zx"
xxxx=1
print(dir())
print(__builtins__)
print(dir(__builtins__))
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'xxxx', 'zx']
<module 'builtins' (built-in)>
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

他也可以使用模块名的方式调用,但是默认可以不写模块名__builtins__

class zx():
    name="zx"
xxxx=1
print(dir())
print(__builtins__)
print(__builtins__.print("找到你啦"))
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'xxxx', 'zx']
<module 'builtins' (built-in)>
找到你啦
None

__builtins__模块的一个小细节

在执行文件中__builtins__是对builtins 模块的引用,而在非执行文件中,是对builtins.__dict__ 的引用

b.py

扫描二维码关注公众号,回复: 7252510 查看本文章
import a
print("b")
print(type(__builtins__))

a.py

print("a")
print(type(__builtins__))
a
<class 'dict'>
b
<class 'module'>

猜你喜欢

转载自www.cnblogs.com/zx125/p/11503830.html