1. 程式人生 > >[py]python的繼承體系

[py]python的繼承體系

ber get from cmd row pos turtle sysconf sort

python的繼承體系

python中一切皆對象
技術分享圖片

隨著類的定義而開辟執行

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)

類的方法

__class__
__delattr__
__dict__
__dir__
__doc__
__eq__
__format__
__ge__
__getattribute__
__gt__
__hash__
__init__
__init_subclass__
__le__
__lt__
__module__
__ne__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__
__weakref__

實例和類存儲

靜態字段
普通字段

普通方法
類方法
靜態方法

字段:
    普通字段
    靜態字段 共享內存

方法都共享內存: 只不過調用方法不同
    普通方法 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']

查看本地環境所有可用模塊


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']

模塊的繼承

技術分享圖片

有個疑問

[py]python的繼承體系