[py]python的继承体系-源码目录结构

时间:2023-03-10 00:43:46
[py]python的继承体系-源码目录结构

[py]python的继承体系-源码目录结构

python3安装目录

pip install virtualenv
pip install virtualenvwrapper
pip install virtualenvwrapper-win
mkvirtualenv --python=C:\Python27\python.exe py27env
exit
mkvirtualenv --python=C:\Python36\python.exe py36env
workon #查看刚刚创建的环境,mkvirtualenv -h查看帮助

[py]python的继承体系-源码目录结构

[py]python的继承体系-源码目录结构

pip安装的第三方包存放位置site-packages

[py]python的继承体系-源码目录结构

安装flask后

pip install -i https://pypi.douban.com/simple flask

[py]python的继承体系-源码目录结构

[py]python的继承体系-源码目录结构

[py]python的继承体系-源码目录结构

python模块查找顺序

['',
'C:\\Users\\Administrator\\Envs\\py36test\\Scripts\\python36.zip', -->系统里没找到
'C:\\Users\\Administrator\\Envs\\py36test\\DLLs', -->虚拟环境貌似不存在
'C:\\Users\\Administrator\\Envs\\py36test\\lib', --> 在lib目录搜模块
'C:\\Users\\Administrator\\Envs\\py36test\\Scripts',
'C:\\Python36\\Lib', ->非虚拟环境里找
'C:\\Python36\\DLLs', ->一些pyd文件
'C:\\Users\\Administrator\\Envs\\py36test',
'C:\\Users\\Administrator\\Envs\\py36test\\lib\\site-packages'] -->pip安装的目录找

Lib下的模块

包含在了help('modules') 里

ls /c/Users/Administrator/Envs/py36test/Lib

__future__.py        genericpath.py               reprlib.py
__pycache__/ hashlib.py rlcompleter.py
_bootlocale.py heapq.py shutil.py
_collections_abc.py hmac.py site.py
_dummy_thread.py imp.py site-packages/
_weakrefset.py importlib/ sre_compile.py
abc.py io.py sre_constants.py
base64.py* keyword.py* sre_parse.py
bisect.py linecache.py stat.py
codecs.py locale.py struct.py
collections/ no-global-site-packages.txt tarfile.py*
copy.py ntpath.py tempfile.py
copyreg.py operator.py token.py
distutils/ orig-prefix.txt tokenize.py
encodings/ os.py types.py
enum.py posixpath.py warnings.py
fnmatch.py random.py weakref.py
functools.py re.py

builtins

包含在了help('modules') 里

object在这个文件里

ls /c/Users/Administrator/.PyCharm2017.3/system/python_stubs/1441790480
array.py
atexit.py
audioop.py
binascii.py
builtins.py
cmath.py
errno.py
faulthandler.py
gc.py
itertools.py
marshal.py
math.py
mmap.py
msvcrt.py
nt.py
parser.py
pyexpat.py
select.py
sys.py
time.py
unicodedata.py
winreg.py
winsound.py
xxsubtype.py
zipimport.py
zlib.py

为什么会认为 Python 是“自带电池”的

help('modules') 显示的模块

如果安装了flask也会检索到flask模块

__future__          _weakref            hashlib             secrets
_ast _weakrefset heapq select
_asyncio _winapi hmac selectors
_bisect abc html setuptools
_blake2 activate_this http shelve
_bootlocale aifc idlelib shlex
_bz2 antigravity imaplib shutil
_codecs argparse imghdr signal
_codecs_cn array imp site
_codecs_hk ast importlib smtpd
_codecs_iso2022 asynchat inspect smtplib
_codecs_jp asyncio io sndhdr
_codecs_kr asyncore ipaddress socket
_codecs_tw atexit itertools socketserver
_collections audioop json sqlite3
_collections_abc base64 keyword sre_compile
_compat_pickle bdb lib2to3 sre_constant
_compression binascii linecache sre_parse
_csv binhex locale ssl
_ctypes bisect logging stat
_ctypes_test builtins lzma statistics
_datetime bz2 macpath string
_decimal cProfile macurl2path stringprep
_dummy_thread calendar mailbox struct
_elementtree cgi mailcap subprocess
_findvs cgitb marshal sunau
_functools chunk math symbol
_hashlib cmath mimetypes symtable
_heapq cmd mmap sys
_imp code modulefinder sysconfig
_io codecs msilib tabnanny
_json codeop msvcrt tarfile
_locale collections multiprocessing telnetlib
_lsprof colorsys netrc tempfile
_lzma compileall nntplib test
_markupbase concurrent nt textwrap
_md5 configparser ntpath this
_msi contextlib nturl2path threading
_multibytecodec copy numbers time
_multiprocessing copyreg opcode timeit
_opcode crypt operator tkinter
_operator csv optparse token
_osx_support ctypes os tokenize
_overlapped curses parser trace
_pickle datetime pathlib traceback
_pydecimal dbm pdb tracemalloc
_pyio decimal pickle tty
_random difflib pickletools turtle
_sha1 dis pip turtledemo
_sha256 distutils pipes types
_sha3 doctest pkg_resources typing
_sha512 dummy_threading pkgutil unicodedata
_signal easy_install platform unittest
_sitebuiltins email plistlib urllib
_socket encodings poplib uu
_sqlite3 ensurepip posixpath uuid
_sre enum pprint venv
_ssl errno profile warnings
_stat faulthandler pstats wave
_string filecmp pty weakref
_strptime fileinput py_compile webbrowser
_struct fnmatch pyclbr wheel
_symtable formatter pydoc winreg
_testbuffer fractions pydoc_data winsound
_testcapi ftplib pyexpat wsgiref
_testconsole functools queue xdrlib
_testimportmultiple gc quopri xml
_testmultiphase genericpath random xmlrpc
_thread getopt re xxsubtype
_threading_local getpass reprlib zipapp
_tkinter gettext rlcompleter zipfile
_tracemalloc glob runpy zipimport
_warnings gzip sched zlib

查看Python当前已装入的模块

结果是一个字典:

>>> sys.modules

{'copy_reg':                                    <module 'copy_reg' from '/usr/lib64/python2.7/copy_reg.pyc'>,
'sre_compile': <module 'sre_compile' from '/usr/lib64/python2.7/sre_compile.pyc'>,
'_sre': <module '_sre' (built-in)>,
'encodings': <module 'encodings' from '/usr/lib64/python2.7/encodings/__init__.pyc'>,
'site': <module 'site' from '/usr/lib64/python2.7/site.pyc'>,
'__builtin__': <module '__builtin__' (built-in)>,
'sysconfig': <module 'sysconfig' from '/usr/lib64/python2.7/sysconfig.pyc'>,
'__main__': <module '__main__' (built-in)>,
'encodings.encodings': None, 'abc': <module 'abc' from '/usr/lib64/python2.7/abc.pyc'>,
'posixpath': <module 'posixpath' from '/usr/lib64/python2.7/posixpath.pyc'>,
'_weakrefset': <module '_weakrefset' from '/usr/lib64/python2.7/_weakrefset.pyc'>,
'errno': <module 'errno' (built-in)>,
'encodings.codecs': None, 'sre_constants': <module 'sre_constants' from '/usr/lib64/python2.7/sre_constants.pyc'>,
're': <module 're' from '/usr/lib64/python2.7/re.pyc'>,
'_abcoll': <module '_abcoll' from '/usr/lib64/python2.7/_abcoll.pyc'>,
'types': <module 'types' from '/usr/lib64/python2.7/types.pyc'>,
'_codecs': <module '_codecs' (built-in)>,
'encodings.__builtin__': None, '_warnings': <module '_warnings' (built-in)>,
'codecs': <module 'codecs' from '/usr/lib64/python2.7/codecs.pyc'>,
'genericpath': <module 'genericpath' from '/usr/lib64/python2.7/genericpath.pyc'>,
'stat': <module 'stat' from '/usr/lib64/python2.7/stat.pyc'>,
'zipimport': <module 'zipimport' (built-in)>,
'_sysconfigdata': <module '_sysconfigdata' from '/usr/lib64/python2.7/_sysconfigdata.pyc'>,
'warnings': <module 'warnings' from '/usr/lib64/python2.7/warnings.pyc'>,
'UserDict': <module 'UserDict' from '/usr/lib64/python2.7/UserDict.pyc'>,
'encodings.utf_8': <module 'encodings.utf_8' from '/usr/lib64/python2.7/encodings/utf_8.pyc'>,
'sys': <module 'sys' (built-in)>,
'repoze': <module 'repoze' (built-in)>,
'readline': <module 'readline' from '/usr/lib64/python2.7/lib-dynload/readline.so'>,
'os.path': <module 'posixpath' from '/usr/lib64/python2.7/posixpath.pyc'>,
'signal': <module 'signal' (built-in)>,
'traceback': <module 'traceback' from '/usr/lib64/python2.7/traceback.pyc'>,
'linecache': <module 'linecache' from '/usr/lib64/python2.7/linecache.pyc'>,
'posix': <module 'posix' (built-in)>,
'encodings.aliases': <module 'encodings.aliases' from '/usr/lib64/python2.7/encodings/aliases.pyc'>,
'exceptions': <module 'exceptions' (built-in)>,
'sre_parse': <module 'sre_parse' from '/usr/lib64/python2.7/sre_parse.pyc'>,
'os': <module 'os' from '/usr/lib64/python2.7/os.pyc'>,
'_weakref': <module '_weakref' (built-in)>}

python的继承体系

python中一切皆对象

a = int(1)                    ## buildin    class int
t = tuple((1,2,3)) ## class str
arr = list([1,2,3,4]) ## class list

[py]python的继承体系-源码目录结构

ls /c/Users/Administrator/.PyCharm2017.3/system/python_stubs/1441790480

[py]python的继承体系-源码目录结构

类的继承

[py]python的继承体系-源码目录结构

[py]python的继承体系-源码目录结构

[py]python的继承体系-源码目录结构

类的定义

参考: 简明Python魔法 - 1

当Python解释器遇到类声明时,会创建一个新的namespace ,并执行其内的所有代码,并将变量注册到这个namespace中。

class Foo(object):
print 'Loading...'
spam = 'eggs'
print 'Done!' class MetaClass(type):
def __init__(cls, name, bases, attrs):
print('Defining %s' % cls)
print('Name: %s' % name)
print('Bases: %s' % (bases,))
print('Attributes:')
for (name, value) in attrs.items():
print(' %s: %r' % (name, value)) class RealClass(object, metaclass=MetaClass):
spam = 'eggs'

判断对象是否属于这个类

class person():pass
p = person()
isinstance(p2,person)

实例和类内存结构

字段:
普通字段
静态字段 共享内存 方法都共享内存: 只不过调用方法不同
普通方法 self
类方法 不需要self
静态方法 cls

查看关键字

from keyword import kwlist
print(kwlist) >>> help()
help> keywords ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

查看本地环境所有可用模块,没显示buildin模块


help('modules') IPython aifc idlelib selectors
__future__ antigravity imaplib setuptools
__main__ argparse imghdr shelve
_ast array imp shlex
_asyncio ast importlib shutil
_bisect asynchat inspect signal
_blake2 asyncio io simplegener
_bootlocale asyncore ipaddress site
_bz2 atexit ipython_genutils six
_codecs audioop itertools smtpd
_codecs_cn autoreload jedi smtplib
_codecs_hk base64 jieba sndhdr
_codecs_iso2022 bdb json socket
_codecs_jp binascii keyword socketserve
_codecs_kr binhex lib2to3 sqlite3
_codecs_tw bisect linecache sre_compile
_collections builtins locale sre_constan
_collections_abc bz2 logging sre_parse
_compat_pickle cProfile lzma ssl
_compression calendar macpath stat
_csv cgi macurl2path statistics
_ctypes cgitb mailbox storemagic
_ctypes_test chunk mailcap string
_datetime cmath markdown stringprep
_decimal cmd marshal struct
_dummy_thread code math subprocess
_elementtree codecs mimetypes sunau
_findvs codeop mmap symbol
_functools collections modulefinder sympyprinti
_hashlib colorama msilib symtable
_heapq colorsys msvcrt sys
_imp compileall multiprocessing sysconfig
_io concurrent netrc tabnanny
_json configparser nntplib tarfile
_locale contextlib nt telnetlib
_lsprof copy ntpath tempfile
_lzma copyreg nturl2path test
_markupbase crypt numbers tests
_md5 csv opcode textwrap
_msi ctypes operator this
_multibytecodec curses optparse threading
_multiprocessing cythonmagic os time
_opcode datetime parser timeit
_operator dbm parso tkinter
_osx_support decimal pathlib token
_overlapped decorator pdb tokenize
_pickle difflib pickle trace
_pydecimal dis pickleshare traceback
_pyio distutils pickletools tracemalloc
_random django pip traitlets
_sha1 django-admin pipes tty
_sha256 doctest pkg_resources turtle
_sha3 dummy_threading pkgutil turtledemo
_sha512 easy_install platform types
_signal email plistlib typing
_sitebuiltins encodings poplib unicodedata
_socket ensurepip posixpath unittest
_sqlite3 enum pprint urllib
_sre errno profile uu
_ssl faulthandler prompt_toolkit uuid
_stat filecmp pstats venv
_string fileinput pty warnings
_strptime fnmatch py_compile wave
_struct formatter pyclbr wcwidth
_symtable fractions pydoc weakref
_testbuffer ftplib pydoc_data webbrowser
_testcapi functools pyexpat wheel
_testconsole gc pygments whoosh
_testimportmultiple genericpath pytz winreg
_testmultiphase getopt queue winsound
_thread getpass quopri wsgiref
_threading_local gettext random xdrlib
_tkinter glob re xml
_tracemalloc gzip reprlib xmlrpc
_warnings hashlib rlcompleter xxsubtype
_weakref haystack rmagic zipapp
_weakrefset heapq runpy zipfile
_winapi hmac sched zipimport
abc html secrets zlib
activate_this http select

dir() 函数: 显示模块属性和方法

__builtin__模块在Python3中重命名为builtins。

In [2]: dir(__builtins__)
Out[2]:
['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',
'PendingDeprecationWarnin
'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',
'__IPYTHON__',
'__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',
'display',
'divmod',
'enumerate',
'eval',
'exec',
'filter',
'float',
'format',
'frozenset',
'get_ipython',
'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',
'range',
'repr',
'reversed',
'round',
'set',
'setattr',
'slice',
'sorted',
'staticmethod',
'str',
'sum',
'super',
'tuple',
'type',
'vars',
'zip']

有个疑问,tuple和list都有index和count方法,难道他们分别各自实现了两遍吗? 源码看不到

python3源码目录-编译安装

$ sudo yum install yum-utils
$ sudo yum-builddep python3
$ wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz
$ tar -xvzf Python-3.5.2.tgz
$ ./configure --prefix=/usr/local/python35
$ make && make install

[py]python的继承体系-源码目录结构

  • Include:Python所有的头文件,写C/C++扩展时需要
  • Lib:Python自带的标准库,Python语言编写
  • Modules:由C语言编写的模块,如ctypes、mutltiprocessing等
  • Parser: Python解释器的Scanner和Parser,即Python的词法分析和语法分析
  • Objects:Python的内建对象的实现、包括list、dict等
  • Python:Python解释器的Compiler和执行引擎
  • PCBuild:Visual Studio工程文件