[py]python的继承体系,,python的继承体


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():passp = 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 kwlistprint(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               zipimportabc                 html                secrets             zlibactivate_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的继承体系

评论关闭