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' , 函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM