日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中import与input_python : import详解。

發布時間:2025/3/20 python 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中import与input_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 *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中))

總結

以上是生活随笔為你收集整理的python中import与input_python : import详解。的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。