python __builtins__ 函数

 dir(__builtins__)

1、'abs', 对传入参数取绝对值

abs(x, /)
    Return the absolute value of the argument.
1 >>> abs(10)
2 10
3 >>> abs(-10)
4 10

2、'all',  用于判断给定的可迭代参数 iterable 中的所有元素是否不为 0、''、False 或者 iterable 为空,如果是返回 True,否则返回 False。

all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.
1 >>> all([1, 2])
2 True
3 >>> all([1, 0])
4 False
5 >>> all([])
6 True

3、'any', 用于判断给定的可迭代参数 iterable 是否全部为空对象,如果都为空、0、false,则返回 False,如果不都为空、0、false,则返回 True。

any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.
1 >>> any([1, 2])
2 True
3 >>> any([1, 0])
4 True
5 >>> any([])
6 False

4、'ascii', 自动执行传入参数的_repr_方法(将对象转换为字符串)

ascii(obj, /)
    Return an ASCII-only representation of an object.
    
    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.
1 >>> ascii(10)
2 '10'
3 >>> ascii('abc')
4 "'abc'"
5 >>> ascii('你妈嗨')
6 "'\\u4f60\\u5988\\u55e8'"

5、'bin', 返回一个整数 int 或者长整数 long int 的二进制表示。

bin(number, /)
    Return the binary representation of an integer.
1 >>> bin(1024)
2 '0b10000000000'

6、'bool',  函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。

7、'bytearray', 返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

8、'bytes', 字符串转换成字节流。第一个传入参数是要转换的字符串,第二个参数按什么编码转换为字节。

9、'callable', 用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。

callable(obj, /)
    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.
1 >>> callable(int)
2 True
3 >>> class Test():
4 ...     def __call__(self):
5 ...         return 1
6 ... 
7 >>> test = Test()
8 >>> test()
9 1

10、'chr', 数字转字符

chr(i, /)
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
1 l = []
2 for i in range(0x10ffff + 1):
3     try:
4         print(i, chr(i), end=" ")
5     except:
6         l.append(i)
7 
8 print(l)
9 print(len(l))

11、'classmethod', 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

12、'compile', 接收.py文件或字符串作为传入参数,将其编译成python字节码

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
    Compile source into a code object that can be executed by exec() or eval().
    
    The source code may represent a Python module, statement or expression.
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if true, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or false these statements do influence the compilation,
    in addition to any features explicitly specified.
>>> str = "for i in range(0,10): print(i)" 
>>> c = compile(str,'','exec')
>>> c
<code object <module> at 0x00000000022EBC00, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str, '', 'eval')
>>> a
<code object <module> at 0x00000000022EB5D0, file "", line 1>
>>> eval(a)
17

13、'complex', 函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

14、'copyright', 版权

15、'credits', 信用

16、'delattr', 用于删除属性。

delattr(obj, name, /)
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
>>> class Test():
...     def __init__(self):
...         self.name  = 'w'
...         self.age = 20
... 
>>> test = Test()
>>> test.name
'w'
>>> test.age
20
>>> delattr(test, 'name')
>>> test.name
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'name'
>>> del test.age
>>> test.age
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'

17、'dict', 用于创建一个字典。

18、'dir', 不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
1 >>> dir()
2 ['__builtins__', '__doc__', '__name__']
3 >>> dir(list)
4 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__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']

19、'divmod',  把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。

1 divmod(x, y, /)
2     Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
1 >>> divmod(10, 3)
2 (3, 1)

20、'dreload', 重新载入模块。

reload(module, exclude=['sys', 'os.path', 'builtins', '__main__'])
    Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
    display, exception, and io hooks.

21、'enumerate', 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

22、'eval', 用来执行一个字符串表达式,并返回表达式的值。

eval(source, globals=None, locals=None, /)
    Evaluate the given 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.
1 >>> x = 10
2 >>> eval('3 * x')
3 30

23、'exec', 执行python代码(可以是编译过的,也可以是未编译的),没有返回结果(返回None)

1 exec(source, globals=None, locals=None, /)
2     Execute the given source in the context of globals and locals.
3     
4     The source may be a string representing one or more Python statements
5     or a code object as returned by compile().
6     The globals must be a dictionary and locals can be any mapping,
7     defaulting to the current globals and locals.
8     If only globals is given, locals defaults to it.
1 >>> exec(compile("print(123)","<string>","exec"))
2 123
3 >>> exec("print(123)")
4 123

24、'filter', 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

25、'float', 用于将整数和字符串转换成浮点数。

26、'format', #字符串格式化

format(value, format_spec='', /)
    Return value.__format__(format_spec)
    
    format_spec defaults to the empty string
1 >>> "{1} {0} {1}".format("hello", "world")
2 'world hello world'
3 >>> "网站名:{name}, 地址 {url}".format(name="教程", url="www.nimahai.com")
4 '网站名:教程, 地址 www.nimahai.com'

27、'frozenset', 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

28、'getattr', 用于返回一个对象属性值。

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.
>>> class Test():
...     def __init__(self):
...         self.name = 'w'
... 
>>> test = Test()
>>> getattr(test, 'name')
'w'
>>> test.name
'w'
>>> getattr(test, 'age')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'
>>> test.age
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'
>>> getattr(test, 'age', 20)
20
>>> test.age
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'

29、'globals', 返回一个字典,包括所有的全局变量与它的值所组成的键值对

globals()
    Return the dictionary containing the current scope's global variables.
    
    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.
a =100
print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000000001E867F0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '1.py', '__cached__': None, 'a': 100}

30、'hasattr', 用于判断对象是否包含对应的属性。

hasattr(obj, name, /)
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
1 class Test():
2     pass
3 
4 test = Test()
5 test.name = 'w'
6 
7 print(hasattr(test, 'name'))
8 print(hasattr(test, 'age'))
1 True
2 False

31、'hash', 对传入参数取哈希值并返回

hash(obj, /)
    Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.
1 print(hash(1))
2 print(hash('test'))
3 print(hash(str([1])))
4 print(hash(str({'1': 1})))

32、'help', 接收对象作为参数,更详细地返回该对象的所有属性和方法

33、'hex', 接收一个十进制,转换成十六进制

hex(number, /)
    Return the hexadecimal representation of an integer.
    
    >>> hex(12648430)
    '0xc0ffee'

34、'id', 返回内存地址,可用于查看两个变量是否指向相同一块内存地址

id(obj, /)
    Return the identity of an object.
    
    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)
1 a = 'string'
2 b = 'string'
3 
4 print(a is b)
5 print(a == b)
6 print(id(a))
7 print(id(b))
1 True
2 True
3 34966640
4 34966640

35、'input',  提示用户输入,返回用户输入的内容(不论输入什么,都转换成字符串类型)

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
1 name = input('enter your name:')
2 print(name)
1 enter your name:w
2 w

36、'int', 用于将一个字符串或数字转换为整型。

37、'isinstance', 判断对象是否是某个类的实例.

1 isinstance(obj, class_or_tuple, /)
2     Return whether an object is an instance of a class or of a subclass thereof.
3     
4     A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
5     check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
6     or ...`` etc.
1 a = (1, 2, 3)
2 print(isinstance(a, (tuple, list, str, int)))
1 True

38、'issubclass', 查看这个类是否是另一个类的派生类,如果是返回True,否则返回False

issubclass(cls, class_or_tuple, /)
    Return whether 'cls' is a derived from another class or is the same class.
    
    A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
    or ...`` etc.
 1 class Animal():
 2     pass
 3 
 4 class Dog(Animal):
 5     pass
 6 
 7 class Person():
 8     pass
 9 
10 
11 print(issubclass(Dog, (Animal, )))
12 print(issubclass(Person, (Animal,)))
True
False

39、'iter', 用来生成迭代器

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.
1 l = ['ss', 'ss"']
2 print(iter(l))
1 <list_iterator object at 0x000000000224BA58>

40、'len', 返回对象(字符、列表、元组等)长度或项目个数。

1 len(obj, /)
2     Return the number of items in a container.
1 l = ['ss', 'ss"']
2 print(len(l))
1 2

41、'license', 许可证,执照

42、'list', 转换为列表类型

43、'locals', 返回一个字典,包括所有的局部变量与它的值所组成的键值对

locals()
    Return a dictionary containing the current scope's local variables.
    
    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is *implementation dependent* and not
    covered by any backwards compatibility guarantees.
1 def test(arg):
2     a = 10
3     print(locals())
4 
5 test(5)
1 {'a': 10, 'arg': 5}

44、'map',  根据提供的函数对指定序列做映射。

45、'max', 接收序列化类型数据,返回其中值最大的元素

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
1 print(max(1, 2, 3, 4))
2 print(max([1, 2, 3, 4]))
3 print(max(*(1, 2), *(1, 2, 3, 4)))
4 print(max(['231', '4232', '213233', 'AFFDSDDFS'], key=len))
5 print(max([], default=19))  # 当可迭代对象为空时,返回默认的对象。
1 4
2 4
3 4
4 AFFDSDDFS
5 19

46、'memoryview',  返回给定参数的内存查看对象(Momory view)。所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。

47、'min', 返回其中值最小的元素

1 min(...)
2     min(iterable, *[, default=obj, key=func]) -> value
3     min(arg1, arg2, *args, *[, key=func]) -> value
4     
5     With a single iterable argument, return its smallest item. The
6     default keyword-only argument specifies an object to return if
7     the provided iterable is empty.
8     With two or more arguments, return the smallest argument.

48、'next', 返回迭代器的下一个项目。

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.
1 it = iter([1, 2, 3, 4, 5])
2 while True:
3     try:
4         x = next(it)
5         print(x)
6     except StopIteration:
7         break
1 1
2 2
3 3
4 4
5 5

49、'object', 

class object
    The most base type

50、'oct', 接收一个十进制,转换成八进制字符串

oct(number, /)
    Return the octal representation of an integer.
    
    >>> oct(342391)
    '0o1234567'

51、'open', 用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise IOError upon failure.
    
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    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 (deprecated)
    ========= ===============================================================
    
    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.
    
    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.

52、'ord', 是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

ord(c, /)
    Return the Unicode code point for a one-character string.
1 print(ord(''))
2 print(ord('A'))
1 20320
2 65

53、'pow', 求次方,返回x**y的结果

pow(x, y, z=None, /)
    Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
    
    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.
1 print(pow(3, 3))
2 print(pow(3, 3, 5))
1 27
2 2

54、'print', 用于打印输出

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.

55、'property',  获取对象的所有属性

56、'range',  创建一个整数列表

57、'repr',  将对象转化为供解释器读取的形式。执行传入对象中的_repr_方法

repr(obj, /)
    Return the canonical string representation of the object.
    
    For many object types, including most builtins, eval(repr(obj)) == obj.
 1 print(repr('abc'))
 2 print(repr([1, 2, 3]))
 3 print(repr({1: 2}))
 4 
 5 class Test():
 6     def __repr__(self):
 7         return 'wwwww'
 8 
 9 test = Test()
10 print(repr(test))
1 'abc'
2 [1, 2, 3]
3 {1: 2}
4 wwwww

58、'reversed',  返回一个反转的迭代器。

59、'round',  返回浮点数x的四舍五入值。

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.
1 print(round(70.11111))
2 print(round(70.55555))
3 print(round(70.11111, 1))
4 print(round(70.55555, 1))
5 print(round(70.11111, 3))
6 print(round(70.55555, 3))
1 70
2 71
3 70.1
4 70.6
5 70.111
6 70.556

60、'set',  转换为集合类型

61、'setattr', 对应函数getattr(),用于设置属性值,该属性必须存在。

setattr(obj, name, value, /)
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
1 class Test():
2     pass
3 
4 test = Test()
5 setattr(test, 'name', 'w')
6 print(test.name)
1 w

62、'slice', 对序列化类型数据切片,返回一个新的对象。

63、'sorted', 对序列化类型数据正向排序,返回一个新的对象。注意与对象的sort方法区别,后者是就地改变对象

sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customise the sort order, and the
    reverse flag can be set to request the result in descending order.
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
1 a = [5, 7, 6, 3, 4, 1, 2]
2 print(sorted(a))
3 
4 l = [('b', 2), ('a', 1), ('c', 3), ('d', 4)]
5 print(sorted(l, key=lambda x: x[1]))
6 
7 students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
8 print(sorted(students, key=lambda s: s[2], reverse=True))
1 [1, 2, 3, 4, 5, 6, 7]
2 [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
3 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

64、'staticmethod', 返回静态方法

65、'str', 字节转换成字符串。第一个传入参数是要转换的字节,第二个参数是按什么编码转换成字符串

66、'sum', 对系列进行求和计算。

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
1 print(sum([1, 2, 3]))
2 print(sum([1, 2, 3], 1))
1 6
2 7

67、'super', 用于调用下一个父类(超类)并返回该父类实例的方法。super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

68、'tuple', 转换为元组类型
69、'type', 返回对象类型
70、'vars', 返回对象object的属性和属性值的字典对象。

vars(...)
    vars([object]) -> dictionary
    
    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.
1 print(vars())
2 
3 class Runoob:
4     a = 1
5 
6 print(vars(Runoob))
7 
8 runoob = Runoob()
9 print(vars(runoob))
1 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000000021C67F0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '2.py', '__cached__': None}
2 {'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Runoob' objects>, '__weakref__': <attribute '__weakref__' of 'Runoob' objects>, '__doc__': None}
3 {}

71、'zip' , 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

 

posted @ 2018-01-05 16:37  魂~  阅读(1656)  评论(0编辑  收藏  举报