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()
实现步骤:
(续上节)
object
>>> help(object)
Help on class object in module builtins:
class object
| The most base type
oct
>>> help(oct)
Help on built-in function oct in module builtins:
oct(...)
oct(number) -> string
Return the octal representation of an integer.
open
>>> help(open)
Help on built-in function open in module io:
open(...)
open(file, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None) -> file object
Open file and return a stream. Raise IOError upon failure.
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (for backwards compatibility; unneeded
for new code)
========= ===============================================================
>>> f = open('1.txt', 'x')
>>> f.write(str(list(range(10))))
30
>>> f.close()
ord
>>> help(ord)
Help on built-in function ord in module builtins:
ord(...)
ord(c) -> integer
Return the integer ordinal of a one-character string.
>>> ord('c')
99
pow
>>> help(pow)
Help on built-in function pow in module builtins:
pow(...)
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
property
>>> help(property)
Help on class property in module builtins:
class property(object)
| property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
|
| fget is a function to be used for getting an attribute value, and likewise
| fset is a function for setting, and fdel a function for del'ing, an
| attribute. Typical use is to define a managed attribute x:
| class C(object):
| def getx(self): return self._x
| def setx(self, value): self._x = value
| def delx(self): del self._x
| x = property(getx, setx, delx, "I'm the 'x' property.")
| Decorators make defining new properties or modifying existing ones easy:
| class C(object):
| @property
| def x(self): return self._x
| @x.setter
| def x(self, value): self._x = value
| @x.deleter
| def x(self): del self._x
|
它具有以下方法
>>> dir(property)
['__class__', '__delattr__', '__delete__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__isabstractmethod__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'deleter', 'fdel', 'fget', 'fset', 'getter', 'setter']
quit
>>> help(quit)
Help on Quitter in module site object:
class Quitter(builtins.object)
range
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return a virtual sequence of numbers from start to stop by step.
它具有以下方法
>>> dir(range)
['__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__',
'__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'count', 'index', 'start', 'step', 'stop']
repr
>>> help(repr)
Help on built-in function repr in module builtins:
repr(...)
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
reversed
>>> help(reversed)
Help on class reversed in module builtins:
class reversed(object)
| reversed(sequence) -> reverse iterator over values of the sequence
|
| Return a reverse iterator
>>> list(reversed(range(5)))
[4, 3, 2, 1, 0]
>>> help(round)
Help on built-in function round in module builtins:
round(...)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
>>> round(1.2345, 3)
1.234
>>> round(1.2347, 3)
1.235
set
>>> help(set)
Help on class set in module builtins:
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
它具有以下方法
>>> dir(set)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__',
'__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__',
'__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__',
'__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
'__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update',
'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset',
'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
setattr
>>> help(setattr)
Help on built-in function setattr in module builtins:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
slice
>>> help(slice)
Help on class slice in module builtins:
class slice(object)
| slice(stop)
| slice(start, stop[, step])
|
| Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
sorted
>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(...)
sorted(iterable, key=None, reverse=False) --> new sorted list
>>> sorted([1,4,2,3])
[1, 2, 3, 4]
staticmethod
>>> help(staticmethod)
Help on class staticmethod in module builtins:
class staticmethod(object)
| staticmethod(function) -> method
|
| Convert a function to be a static method.
|
| A static method does not receive an implicit first argument.
| To declare a static method, use this idiom:
|
| class C:
| def f(arg1, arg2, ...): ...
| f = staticmethod(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.
str
>>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
>>> "about".center(10, ' ')
' about '
它具有以下方法
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', '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']
sum
>>> help(sum)
Help on built-in function sum in module builtins:
sum(...)
sum(iterable[, start]) -> value
Return the sum of an iterable of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the iterable is
empty, return start.
>>> sum(range(101))
5050
super
>>> help(super)
Help on class super in module builtins:
class super(object)
| super() -> same as super(__class__, <first argument>)
| super(type) -> unbound super object
| super(type, obj) -> bound super object; requires isinstance(obj, type)
| super(type, type2) -> bound super object; requires issubclass(type2, type)
| Typical use to call a cooperative superclass method:
| class C(B):
| def meth(self, arg):
| super().meth(arg)
| This works for class methods too:
| class C(B):
| @classmethod
| def cmeth(cls, arg):
| super().cmeth(arg)
tuple
>>> help(tuple)
Help on class tuple in module builtins:
class tuple(object)
| tuple() -> empty tuple
| tuple(iterable) -> tuple initialized from iterable's items
|
| If the argument is a tuple, the return value is the same object.
>>> tuple([1,2,4])
(1, 2, 4)
>>> _.count(1)
1
>>> tuple([1,2,4]).index(4)
2
它具有以下方法
>>> dir(tuple)
['__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__', 'count', 'index']
type
>>> help(type)
Help on class type in module builtins:
class type(object)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
>>> Exception.mro()
[<class 'Exception'>, <class 'BaseException'>, <class 'object'>]
vars
>>> help(vars)
Help on built-in function vars in module builtins:
vars(...)
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
zip
>>> help(zip)
Help on class zip in module builtins:
class zip(object)
| zip(iter1 [,iter2 [...]]) --> zip object
|
| Return a zip object whose .__next__() method returns a tuple where
| the i-th element comes from the i-th iterable argument. The .__next__()
| method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises StopIteration.
>>> z = zip(range(5), range(3))
>>> z.__next__()
(0, 0)
>>> z.__next__()
(1, 1)
>>> z.__next__()
(2, 2)
>>> z.__next__()
Traceback (most recent call last):
File "<pyshell#148>", line 1, in <module>
z.__next__()
StopIteration
__import__
>>> 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.
=>
到此内置函数全部浏览完毕,下面我来做一个总结。
在这68个内置函数中,首先我看的是help()和dir(),它们会指示出任何类和函数的用法和所含有的方法和属性,是最好的手册。
其次是集合容器,有bytearray, bytes, frozenset, set, dict, list, map, tuple, zip, enumerate, 另外range, slice,也可以算到其中
其次是对集合的操作,有sorted, reversed, iter, next, 另有对元素进行的过滤,有all, any, filter
其次是一些数学操作,有abs, max, min, round, sum, pow, divmod, 进制的转换,有bin, oct, hex, 数字和字符之间的转换,有ascii, chr, ord, str, format
其次是数据类型的转换,有bool ,int, float, complex, type, object,
其次是属性,变量等,有len, delattr, getattr, setattr, hasattr, property, vars, globals, locals, hash, id, classmethod, staticmethod, super, isinstance, issubclass,
其次是最笼统的操作,有exec, compile, repr, eval, memoryview, __import__
其次是输入输出,有open, print,
这样就全部分类完毕
本节到此结束