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的继承体系-源码目录结构的更多相关文章

  1. Source Code Structure - Python 源码目录结构

    Source Code Structure - Python 源码目录结构 Include 目录包含了 Python 提供的所有头文件, 如果用户需要用 C 或 C++ 编写自定义模块扩展 Pytho ...

  2. Linux基础系列—Linux内核源码目录结构

    /** ****************************************************************************** * @author    暴走的小 ...

  3. 【安卓本卓】Android系统源码篇之(一)源码获取、源码目录结构及源码阅读工具简介

    前言        古人常说,“熟读唐诗三百首,不会作诗也会吟”,说明了大量阅读诗歌名篇对学习作诗有非常大的帮助.做开发也一样,Android源码是全世界最优秀的Android工程师编写的代码,也是A ...

  4. InfluxDB源码目录结构解析

    操作系统 : CentOS7.3.1611_x64 go语言版本:1.8.3 linux/amd64 InfluxDB版本:1.1.0 influxdata主目录结构 [root@localhost ...

  5. chromium浏览器开发系列第三篇:chromium源码目录结构

    上两篇介绍了下载源码和编译源码,这次主要介绍chromium的源码目录结构,我也是通过源码和官网结合来跟大家说,如果有说的不准确的,欢迎交流. 另外,官网的不一定准确,他们其实也很懒,所以最主要还是靠 ...

  6. (转)android系统架构及源码目录结构

    转自:http://blog.csdn.net/finewind/article/details/46324507 1. Android系统架构: android系统架构采用了分层架构的思想,如下图所 ...

  7. (3.1)mysql基础深入——mysql二进制与源码目录结构介绍

    (3.1)mysql基础深入——mysql二进制与源码目录结构介绍 关键字:二进制目录结构,源码目录结构(编译安装目录结构) 1.二进制安装程序目录结构 [1] BIN -- mysql的可执行文件( ...

  8. Locust源码目录结构及模块作用

    Locust源码目录结构及模块作用如下: 参考文章:https://blog.csdn.net/biheyu828/article/details/84031942

  9. [py]python的继承体系

    python的继承体系 python中一切皆对象 随着类的定义而开辟执行 class Foo(object): print 'Loading...' spam = 'eggs' print 'Done ...

随机推荐

  1. Android textview及其子类

    属性: android:autoLink设置是否当文本为URL链接/email/电话号码/map时,文本显示为可点击的链接.可选值(none/web/email/phone/map/all) andr ...

  2. 在PowerDesigner中自动生成sqlserver字段备注

    在PowerDesigner中自动生成sqlserver字段备注 PowerDesigner是数据库设计人员常用的设计工具,但其自生默认生成的代码并不会生成sqlserver数据库的字段备注说明.在生 ...

  3. MapReduce模型探究--总览

    先从宏观上了解一下MR运行机制. 两个干活的: (1)jobtracher:管理和调度job (2)tasktracher: 执行job划分后的task client提交MR作业后,jobtrache ...

  4. activeMQ---->ActiveMQ的使用(一)

    这里通过一个入门的案例来体会一下ActiveMQ的作用以及使用方法.你要做一个不动声色的大人了.不准情绪化,不准偷偷想念,不准回头看.去过自己另外的生活.你要听话,不是所有的鱼都会生活在同一片海里. ...

  5. css方法 - 移动端reset汇总与注释

    1.解决移动端触摸a元素,会有蓝色阴影 正常状态: 点击时状态: a{ outline:none; -webkit-tap-highlight-color: rgba(,,,); } -webkit- ...

  6. Elasticsearch学习之深入搜索三 --- best fields策略

    1. 为帖子数据增加content字段 POST /forum/article/_bulk { "} } { "doc" : {"content" : ...

  7. gradle项目,连同依赖一起打jar包

    在build里加入以下配置(如果不是一个可执行的jar包的话就不用配置Main-Class属性): def mainClassName = "你需要执行的main方法所在的的包名+类名&qu ...

  8. 编译安装Ruby 1.9.3 安装CentOS

    1. 准备需要的安装的东西 yum -y install make gcc openssl-devel zlib-devel gcc gcc-c++ make autoconf readline-de ...

  9. Unity3D笔记十三 摄像机之间切换

    using UnityEngine; using System.Collections; public class _5_6 : MonoBehaviour { private GameObject ...

  10. Xcode - 打开工程,提示No Scheme解决

    错误提示,如图: 解决思路: