python的继承体系

python中一切皆对象

[py]python的继承体系-LMLPHP

随着类的定义而开辟执行

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的继承体系-LMLPHP

有个疑问

05-11 18:12