[从头学python] 第01节 python标准库里有什么

使用工具:

Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:18:40) [MSC v.1600 32 bit (Intel)] on win32, Type "copyright", "credits" or "license()" for more information.

本节目标:
(1) 了解python标准库, 使用68种内置函数中的若干种来查看python标准库
(2) 使用内置函数dir(), help(), classmethod(), staticmethod(), id(), type(), vars(), property(),isinstance(), issubclass(), callable()
(3) 使用print()
(4) 使用__import__(), globals(), locals()


实现步骤:

在python 3.3的帮助手册中,介绍了下面这些内置函数

节我将要通过使用help()和dir(),来学会所有的这些内置函数。

先看dir()

>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__']

=>

>>> dir(__builtins__)
['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', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', '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', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

=> 发现很多的*Error, *Exception, *Warning,了解一下

>>> help(KeyboardInterrupt)
Help on class KeyboardInterrupt in module builtins:

class KeyboardInterrupt(BaseException)
 |  Program interrupted by user.
 |  
 |  Method resolution order:
 |      KeyboardInterrupt
 |      BaseException
 |      object
 
>>> help(None)
Help on NoneType object:

class NoneType(object)

>>> help(NotImplemented)
Help on NotImplementedType object:

class NotImplementedType(object)

>>> help(OverflowError)
Help on class OverflowError in module builtins:

class OverflowError(ArithmeticError)
 |  Result too large to be represented.
 |  
 |  Method resolution order:
 |      OverflowError
 |      ArithmeticError
 |      Exception
 |      BaseException
 |      object
 
>>> issubclass(OverflowError, Exception)
True

>>> help(ResourceWarning)
Help on class ResourceWarning in module builtins:

class ResourceWarning(Warning)
 |  Base class for warnings about resource usage.
 |  
 |  Method resolution order:
 |      ResourceWarning
 |      Warning
 |      Exception
 |      BaseException
 |      object
 |  
 |  Methods defined here:
 
>>> help(RuntimeError)
Help on class RuntimeError in module builtins:

class RuntimeError(Exception)
 |  Unspecified run-time error.
 |  
 |  Method resolution order:
 |      RuntimeError
 |      Exception
 |      BaseException
 |      object
 
>>> help(RuntimeWarning)
Help on class RuntimeWarning in module builtins:

class RuntimeWarning(Warning)
 |  Base class for warnings about dubious runtime behavior.
 |  
 |  Method resolution order:
 |      RuntimeWarning
 |      Warning
 |      Exception
 |      BaseException
 |      object
 
>>> help(Warning)
Help on class Warning in module builtins:

class Warning(Exception)
 |  Base class for warning categories.
 |  
 |  Method resolution order:
 |      Warning
 |      Exception
 |      BaseException
 |      object
 
>>> help(object)
Help on class object in module builtins:

class object
 |  The most base type
 
>>> help(BaseException)
Help on class BaseException in module builtins:

class BaseException(object)
 |  Common base class for all exceptions
 
>>> help(_)
Help on bool object:

class bool(int)
 |  bool(x) -> bool
 
>>> help(__build_class__)
Help on built-in function __build_class__ in module builtins:

__build_class__(...)
    __build_class__(func, name, *bases, metaclass=None, **kwds) -> class
    
    Internal helper function used by the class statement.
	
>>> help(__debug__)
Help on bool object:

class bool(int)
 |  bool(x) -> bool

>>> help(__doc__)
Help on NoneType object:

class NoneType(object)

>>> help(__import__)
Help on built-in function __import__ in module builtins:

__import__(...)
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
    
    Import a module. Because this function is meant for use by the Python
    interpreter and not for general use it is better to use
    importlib.import_module() to programmatically import a module.
	
>>> help(__loader__)
Help on class BuiltinImporter in module importlib._bootstrap:

class BuiltinImporter(builtins.object)
 |  Meta path import for built-in modules.
 |  
 |  All methods are either class or static methods to avoid the need to
 |  instantiate the class.
 
>>> help(__name__)
Help on module __main__:

NAME
    __main__

FILE
    (built-in)
	
>>> help(__package__)
Help on NoneType object:

class NoneType(object)

=> 进入正题

abs

>>> help(abs)
Help on built-in function abs in module builtins:

abs(...)
    abs(number) -> number
    
    Return the absolute value of the argument.
	
>>> callable(abs)
True

all 和 any

>>> help(all)
Help on built-in function all in module builtins:

all(...)
    all(iterable) -> bool
    
    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

>>> callable(all)
True

>>> a = all(iter([1, 2, 3]))
>>> a
True

>>> help(any)
Help on built-in function any in module builtins:

any(...)
    any(iterable) -> bool
    
    Return True if bool(x) is True for any x in the iterable.
    If the iterable is empty, return False.
	
>>> all([0, 1, 2])
False

>>> any([0, 1, 2])
True

ascii

>>> help(ascii)
Help on built-in function ascii in module builtins:

ascii(...)
    ascii(object) -> string
    
    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \x, \u or \U escapes.  This generates a string similar
    to that returned by repr() in Python 2.
	
>>> ascii("我在学Python")
"'\\u6211\\u5728\\u5b66Python'"

bin

>>> help(bin)
Help on built-in function bin in module builtins:

bin(...)
    bin(number) -> string
    
    Return the binary representation of an integer.
	
>>> bin(1023)
'0b1111111111'

bool

>>> help(bool)
Help on class bool in module builtins:

class bool(int)
 |  bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.
 |  
 |  Method resolution order:
 |      bool
 |      int
 |      object
 
>>> complex(1,2).conjugate()
(1-2j)
>>> (2+3j).conjugate()
(2-3j)

>>> int.from_bytes([1,1,1,1], 'big')
16843009
>>> int.from_bytes([1,1,1,1], 'little')
16843009
>>> int.from_bytes([1], 'big')
1
>>> int.from_bytes([1, 1], 'big')
257

>>> int.from_bytes([1, 255], 'big')
511
>>> int.from_bytes([1, 1001], 'big')
Traceback (most recent call last):
  File "<pyshell#93>", line 1, in <module>
    int.from_bytes([1, 1001], 'big')
ValueError: bytes must be in range(0, 256)

bytearray

>>> help(bytearray)
Help on class bytearray in module builtins:

class bytearray(object)
 |  bytearray(iterable_of_ints) -> bytearray
 |  bytearray(string, encoding[, errors]) -> bytearray
 |  bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
 |  bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
 |  bytearray() -> empty bytes array
 |  
 |  Construct an mutable bytearray object from:
 |    - an iterable yielding integers in range(256)
 |    - a text string encoded using the specified encoding
 |    - a bytes or a buffer object
 |    - any object implementing the buffer API.
 |    - an integer

它有以下方法

>>> dir(bytearray)
['__add__', '__alloc__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'capitalize', 'center', 'clear', 'copy', 'count', 'decode', 'endswith', 'expandtabs', 'extend', 'find', 'fromhex', 'index', 'insert', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'pop', 'remove', 'replace', 'reverse', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

bytes

>>> help(bytes)
Help on class bytes in module builtins:

class bytes(object)
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(int) -> bytes object of size given by the parameter initialized with null bytes
 |  bytes() -> empty bytes object
 |  
 |  Construct an immutable array of bytes from:
 |    - an iterable yielding integers in range(256)
 |    - a text string encoded using the specified encoding
 |    - any object implementing the buffer API.
 |    - an integer

它有以下方法

>>> dir(bytes)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

callable

>>> help(callable)
Help on built-in function callable in module builtins:

callable(...)
    callable(object) -> bool
    
    Return whether the object is callable (i.e., some kind of function).
    Note that classes are callable, as are instances of classes with a
    __call__() method.


chr

>>> help(chr)
Help on built-in function chr in module builtins:

chr(...)
    chr(i) -> Unicode character
    
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.


classmethod

>>> help(classmethod)
Help on class classmethod in module builtins:

class classmethod(object)
 |  classmethod(function) -> method
 |  
 |  Convert a function to be a class method.
 |  
 |  A class method receives the class as implicit first argument,
 |  just like an instance method receives the instance.
 |  To declare a class method, use this idiom:
 |  
 |    class C:
 |        def f(cls, arg1, arg2, ...): ...
 |        f = classmethod(f)
 |  
 |  It can be called either on the class (e.g. C.f()) or on an instance
 |  (e.g. C().f()).  The instance is ignored except for its class.
 |  If a class method is called for a derived class, the derived class
 |  object is passed as the implied first argument.

compile

>>> help(compile)
Help on built-in function compile in module builtins:

compile(...)
    compile(source, filename, mode[, flags[, dont_inherit]]) -> code object

complex

>>> help(complex)
Help on class complex in module builtins:

class complex(object)
 |  complex(real[, imag]) -> complex number
 |  
 |  Create a complex number from a real part and an optional imaginary part.
 |  This is equivalent to (real + imag*1j) where imag defaults to 0.
 
>>> (1+2j).__mul__(1-3j)
(7-1j)

它具有以下方法

>>> dir(complex)
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'conjugate', 'imag', 'real']

delattr

>>> help(delattr)
Help on built-in function delattr in module builtins:

delattr(...)
    delattr(object, name)
    
    Delete a named attribute on an object; delattr(x, 'y') is equivalent to
    ``del x.y''.

dict

>>> help(dict)
Help on class dict in module builtins:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  

>>> dict([[1,2], [2,3]])
{1: 2, 2: 3}

它具有以下方法

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

dir

>>> help(dir)
Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings

divmod

>>> help(divmod)
Help on built-in function divmod in module builtins:

divmod(...)
    divmod(x, y) -> (div, mod)
    
    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
	
>>> divmod(1000, 7)
(142, 6)

enumerate

>>> help(enumerate)
Help on class enumerate in module builtins:

class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |  
 |  Return an enumerate object.  iterable must be another object that supports
 |  iteration.  The enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
 
>>> enumerate([5, 4, 3], 0)
<enumerate object at 0x0109ADF0>
>>> dict(enumerate([5, 4, 3]))
{0: 5, 1: 4, 2: 3}

eval 和 exec

>>> help(eval)
Help on built-in function eval in module builtins:

eval(...)
    eval(source[, globals[, locals]]) -> value
    
    Evaluate the source in the context of globals and locals.
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
	
>>> eval("1+2")
3

>>> help(exec)
Help on built-in function exec in module builtins:

exec(...)
    exec(object[, globals[, locals]])
    
    Read and execute code from an object, which can be a string or a code
    object.
    The globals and locals are dictionaries, defaulting to the current
    globals and locals.  If only globals is given, locals defaults to it.
	
>>> exec("1+2")
>>> _
3

filter

>>> help(filter)
Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 
>>> def f(x):return x!=0
>>> dict(enumerate(filter(f, [1,2,0,4])))
{0: 1, 1: 2, 2: 4}
>>> str(filter(f, [1,2,0,4]))
'<filter object at 0x0108CB90>'

float

>>> help(float)
Help on class float in module builtins:

class float(object)
 |  float(x) -> floating point number
 |  
 |  Convert a string or number to a floating point number, if possible.

format

>>> help(format)
Help on built-in function format in module builtins:

format(...)
    format(value[, format_spec]) -> string
    
    Returns value.__format__(format_spec)
    format_spec defaults to ""

frozenset

>>> help(frozenset)
Help on class frozenset in module builtins:

class frozenset(object)
 |  frozenset() -> empty frozenset object
 |  frozenset(iterable) -> frozenset object
 |  
 |  Build an immutable unordered collection of unique elements.

它具有以下方法

>>> dir(frozenset)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']

getattr

>>> help(getattr)
Help on built-in function getattr in module builtins:

getattr(...)
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.

globals

>>> help(globals)
Help on built-in function globals in module builtins:

globals(...)
    globals() -> dictionary
    
    Return the dictionary containing the current scope's global variables.
	
>>> globals()
{'__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__'}

hasattr

>>> help(hasattr)
Help on built-in function hasattr in module builtins:

hasattr(...)
    hasattr(object, name) -> bool
    
    Return whether the object has an attribute with the given name.
    (This is done by calling getattr(object, name) and catching AttributeError.)

hash

>>> help(hash)
Help on built-in function hash in module builtins:

hash(...)
    hash(object) -> integer
    
    Return a hash value for the object.  Two objects with the same value have
    the same hash value.  The reverse is not necessarily true, but likely.

hex

>>> help(hex)
Help on built-in function hex in module builtins:

hex(...)
    hex(number) -> string
    
    Return the hexadecimal representation of an integer.

id

>>> help(id)
Help on built-in function id in module builtins:

id(...)
    id(object) -> integer
    
    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

input

>>> help(input)
Help on built-in function input in module builtins:

input(...)
    input([prompt]) -> string
    
    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.
	

int

>>> help(int)
Help on class int in module builtins:

class int(object)
 |  int(x=0) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 
>>> int('0b100', base=2)
4

它具有以下方法

>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

isinstance

>>> help(isinstance)
Help on built-in function isinstance in module builtins:

isinstance(...)
    isinstance(object, class-or-type-or-tuple) -> bool
    
    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).

issubclass

>>> help(issubclass)
Help on built-in function issubclass in module builtins:

issubclass(...)
    issubclass(C, B) -> bool
    
    Return whether class C is a subclass (i.e., a derived class) of class B.
    When using a tuple as the second argument issubclass(X, (A, B, ...)),
    is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).

iter

>>> help(iter)
Help on built-in function iter in module builtins:

iter(...)
    iter(iterable) -> iterator
    iter(callable, sentinel) -> iterator
    
    Get an iterator from an object.  In the first form, the argument must
    supply its own iterator, or be a sequence.
    In the second form, the callable is called until it returns the sentinel.

>>> for i in iter(range(5)):print(i*2)

0
2
4
6
8

len

>>> help(len)
Help on built-in function len in module builtins:

len(...)
    len(object) -> integer
    
    Return the number of items of a sequence or mapping.
	
>>> len(range(5))
5

license

>>> help(license)
Help on _Printer in module site object:

class _Printer(builtins.object)
 |  interactive prompt objects for printing the license text, a list of
 |  contributors and the copyright notice.

list

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items

它具有以下方法

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

locals

>>> help(locals)
Help on built-in function locals in module builtins:

locals(...)
    locals() -> dictionary
    
    Update and return a dictionary containing the current scope's local variables.

>>> locals()
{'i': 4, '__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__'}

map

>>> help(map)
Help on class map in module builtins:

class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.

>>> dict(enumerate(map(lambda x: x * 2, [1,2,4])))
{0: 2, 1: 4, 2: 8}

>>> list(map(lambda x: x * 2, [1,2,4]))
[2, 4, 8]

max 和 min

>>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value
    
    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

>>> help(min)
Help on built-in function min in module builtins:


min(...)
    min(iterable[, key=func]) -> value
    min(a, b, c, ...[, key=func]) -> value
    
    With a single iterable argument, return its smallest item.
    With two or more arguments, return the smallest argument.

memoryview

>>> help(memoryview)
Help on class memoryview in module builtins:

class memoryview(object)
 |  memoryview(object)
 |  
 |  Create a new memoryview object which references the given object.
 | 

next

>>> help(next)
Help on built-in function next in module builtins:

next(...)
    next(iterator[, default])
    
    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.

(此节为上半篇,未完待续)


你可能感兴趣的:([从头学python] 第01节 python标准库里有什么)