[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查看帮助


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

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



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

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

类的继承



类的定义
参考: 简明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

- 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工程文件
[py]python的继承体系-源码目录结构的更多相关文章
- Source Code Structure - Python 源码目录结构
Source Code Structure - Python 源码目录结构 Include 目录包含了 Python 提供的所有头文件, 如果用户需要用 C 或 C++ 编写自定义模块扩展 Pytho ...
- Linux基础系列—Linux内核源码目录结构
/** ****************************************************************************** * @author 暴走的小 ...
- 【安卓本卓】Android系统源码篇之(一)源码获取、源码目录结构及源码阅读工具简介
前言 古人常说,“熟读唐诗三百首,不会作诗也会吟”,说明了大量阅读诗歌名篇对学习作诗有非常大的帮助.做开发也一样,Android源码是全世界最优秀的Android工程师编写的代码,也是A ...
- InfluxDB源码目录结构解析
操作系统 : CentOS7.3.1611_x64 go语言版本:1.8.3 linux/amd64 InfluxDB版本:1.1.0 influxdata主目录结构 [root@localhost ...
- chromium浏览器开发系列第三篇:chromium源码目录结构
上两篇介绍了下载源码和编译源码,这次主要介绍chromium的源码目录结构,我也是通过源码和官网结合来跟大家说,如果有说的不准确的,欢迎交流. 另外,官网的不一定准确,他们其实也很懒,所以最主要还是靠 ...
- (转)android系统架构及源码目录结构
转自:http://blog.csdn.net/finewind/article/details/46324507 1. Android系统架构: android系统架构采用了分层架构的思想,如下图所 ...
- (3.1)mysql基础深入——mysql二进制与源码目录结构介绍
(3.1)mysql基础深入——mysql二进制与源码目录结构介绍 关键字:二进制目录结构,源码目录结构(编译安装目录结构) 1.二进制安装程序目录结构 [1] BIN -- mysql的可执行文件( ...
- Locust源码目录结构及模块作用
Locust源码目录结构及模块作用如下: 参考文章:https://blog.csdn.net/biheyu828/article/details/84031942
- [py]python的继承体系
python的继承体系 python中一切皆对象 随着类的定义而开辟执行 class Foo(object): print 'Loading...' spam = 'eggs' print 'Done ...
随机推荐
- 【python3】基于 qq邮箱的邮件发送
脚本内容: #!/usr/bin/python3 # -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText ...
- JS - 二叉树算法实现与遍历 (更新中...)
一.关于二叉树: 截图来自:https://segmentfault.com/a/1190000000740261 温馨提示:学习以及使用二叉树概念,心中永远有这么一个图,对于理解和接受二叉树有很大的 ...
- 题目1461:Tempter of the bone(深度优先遍历DFS)
题目链接:http://ac.jobdu.com/problem.php?pid=1461 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...
- Visual Studio 2012创建SQL Server Database Project提示失败解决方法
新建一个SQL Server Database Project,提示: Unable to open Database project This version of SQL Server Data ...
- soanr - 企业用户角色管理
首先sonar支持群组 即 支持企业角色权限管理,其次sonar支持单项目用户权限管理 即 外包,客户,外编人员用户权限管理. (视图内可看到源码) 按照 管路员.产品/项目管理.产品/项目开发.外包 ...
- C++ 标准输出cout与printf
C++标准输出cout与printf都可以,printf用法更死板一些. #include <iostream> int main(int argc, char** argv) { usi ...
- vue--父子组件的传值
什么是父子组件? 组件中引入组件,被引入的组件就是子组件.例如在 Hello.vue 组件中引入 Header.vue 组件,那么 Hello.vue 就是父组件,Header.vue就是子组件. 一 ...
- Java 多线程 ---- 线程中this与 Thread.currentThread()线程的区别
总结起来一句话:在Thread中调用this其实就是调用Thread私有Runnable类型的target,target是Thread类的一个属性,而Thread.currentThread()是指新 ...
- Centos7 安装hive
安装hive 配置hive 在hdfs中新建目录/user/hive/warehouse 首先启动hadoop任务 hdfs dfs -mkdir /tmp hdfs dfs -mkdir /user ...
- 洛谷P2414 阿狸的打字机【AC自动机】【fail树】【dfs序】【树状数组】
居然真的遇上了这种蔡队题.瑟瑟发抖. 题目背景 阿狸喜欢收藏各种稀奇古怪的东西,最近他淘到一台老式的打字机. 题目描述 打字机上只有28个按键,分别印有26个小写英文字母和'B'.'P'两个字母.经阿 ...