Python 新版本有75个内置函数,你不会不知道吧

Python 内置函数详解 (2) 逻辑运算 阅读详情

目录

Python 内置函数

前言

属性分类

模块 module

29. format()

35. help()

对象 object

17. copyright()

18. credits()

26. exit()

44. license()

59. quit()

类 class

08. bool()

10. bytearray()

11. bytes()

14. classmethod()

16. complex()

20. dict()

23. enumerate()

27. filter()

28. float()

30. frozenset()

39. int()

45. list()

47. map()

49. memoryview()

52. object()

58. property()

60. range()

62. reversed()

64. set()

66. slice()

68. staticmethod()

69. str()

71. super()

72. tuple()

73. type()

75. zip()

内置函数 built-in function

01. abs()

02. aiter()

03. all()

04. anext()

05. any()

06. ascii()

07. bin()

09. breakpoint()

12. callable()

13. chr()

15. compile()

19. delattr()

21. dir()

22. divmod()

24. eval()

25. exec()

31. getattr()

32. globals()

33. hasattr()

34. hash()

36. hex()

37. id()

38. input()

40. isinstance()

41. issubclass()

42. iter()

43. len()

46. locals()

48. max()

50. min()

51. next()

53. oct()

54. open()

55. ord()

56. pow()

57. print()

61. repr()

63. round()

65. setattr()

67. sorted()

70. sum()

74. vars()

功能分类

数学运算

逻辑运算

输入输出

进制转换

类型转换

迭代器

文件操作

排序操作

代码执行

对象属性

属性操作

变量和作用域


Python 内置函数

前言

网上多流传68个内置函数,不管是68还75都对,因为所在版本不一样。但是新版本3.11已经有75个内置函数,再说“python有68个内置函数,你不会不知道吧”就有点落后了。

68一说的版本中把__import__也算进去,它可以在一行内导入库并引入库函数,把这加进去说成有76个的版本也是可以的。关于__import__的用法,例如:

导入sys标准库,查询我的python版本号:

>>> __import__('sys').winver
'3.11'
>>> __import__('sys').version
'3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]'
>>> __import__('sys').version_info
sys.version_info(major=3, minor=11, micro=0, releaselevel='final', serial=0)

等价于:

>>> import sys
>>> sys.winver
'3.11'
>>> sys.version
'3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]'
>>> sys.version_info
sys.version_info(major=3, minor=11, micro=0, releaselevel='final', serial=0)

查阅3.11版本中的函数及个数

>>> [i for i in dir(__builtins__) if i[0]>='a']
['abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', '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']
>>> len([i for i in dir(__builtins__) if i[0]>='a'])
75
>>> # 按字母序给函数编上号:
>>> for i,fn in enumerate(i for i in dir(__builtins__) if i[0]>='a'):
...     if i%5==0: print()
...     fn = f"{fn}()"
...     print(f'{i+1:02}-{fn:15}', end='')
... 
...     

01-abs()          02-aiter()        03-all()          04-anext()        05-any()          
06-ascii()        07-bin()          08-bool()         09-breakpoint()   10-bytearray()    
11-bytes()        12-callable()     13-chr()          14-classmethod()  15-compile()      
16-complex()      17-copyright()    18-credits()      19-delattr()      20-dict()         
21-dir()          22-divmod()       23-enumerate()    24-eval()         25-exec()         
26-exit()         27-filter()       28-float()        29-format()       30-frozenset()    
31-getattr()      32-globals()      33-hasattr()      34-hash()         35-help()         
36-hex()          37-id()           38-input()        39-int()          40-isinstance()   
41-issubclass()   42-iter()         43-len()          44-license()      45-list()         
46-locals()       47-map()          48-max()          49-memoryview()   50-min()          
51-next()         52-object()       53-oct()          54-open()         55-ord()          
56-pow()          57-print()        58-property()     59-quit()         60-range()        
61-repr()         62-reversed()     63-round()        64-set()          65-setattr()      
66-slice()        67-sorted()       68-staticmethod() 69-str()          70-sum()          
71-super()        72-tuple()        73-type()         74-vars()         75-zip()          

这就是新版的“75个内置函数”一说的由来。

属性分类

其实这75个不全是真正的“内置函数”,它们其中还有属于 module(2个),object(5个),class(26个) 三种情况的,真正的内置函数只有42个。

模块 module

2个模块,format和help。

29. format()

Help on module format:

NAME
    format - Format all or a selected region (line slice) of text.

MODULE REFERENCE
    https://docs.python.org/3.11/library/format.html
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    Region formatting options: paragraph, comment block, indent, deindent,
    comment, uncomment, tabify, and untabify.
    
    File renamed from paragraph.py with functions added from editor.py.

CLASSES
    builtins.object
        FormatParagraph
        FormatRegion
        Indents
        Rstrip

FILE
    d:\program files\python\lib\idlelib\format.py
>>> import format
>>> dir(format)
['FormatParagraph', 'FormatRegion', 'Indents', 'Rstrip', '__builtins__', '__cached__', 
'__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 
'_line_indent_re', 'askinteger', 'askyesno', 'find_paragraph', 'get_comment_header', 
'get_indent', 'get_line_indent', 'idleConf', 'is_all_white', 're', 'reformat_comment', 
'reformat_paragraph']

35. help()

Help on module help:

NAME
    help

MODULE REFERENCE
    https://docs.python.org/3.11/library/help.html
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    help.py: Implement the Idle help menu.
    Contents are subject to revision at any time, without notice.
    
    
    Help => About IDLE: display About Idle dialog
    
    <to be moved here from help_about.py>
    
    
    Help => IDLE Help: Display help.html with proper formatting.
    Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html
    (help.copy_strip)=> Lib/idlelib/help.html
    
    HelpParser - Parse help.html and render to tk Text.
    
    HelpText - Display formatted help.html.
    
    HelpFrame - Contain text, scrollbar, and table-of-contents.
    (This will be needed for display in a future tabbed window.)
    
    HelpWindow - Display HelpFrame in a standalone window.
    
    copy_strip - Copy idle.html to help.html, rstripping each line.
    
    show_idlehelp - Create HelpWindow.  Called in EditorWindow.help_dialog.

CLASSES
    html.parser.HTMLParser(_markupbase.ParserBase)
        HelpParser
    tkinter.Text(tkinter.Widget, tkinter.XView, tkinter.YView)
        HelpText
    tkinter.Toplevel(tkinter.BaseWidget, tkinter.Wm)
        HelpWindow
    tkinter.ttk.Frame(tkinter.ttk.Widget)
        HelpFrame

FILE
    d:\program files\python\lib\idlelib\help.py
>>> import help
>>> dir(help)
['Frame', 'HTMLParser', 'HelpFrame', 'HelpParser', 'HelpText', 'HelpWindow', 'Menu', 
'Menubutton', 'Scrollbar', 'Text', 'Toplevel', '__builtins__', '__cached__', '__doc__', 
'__file__', '__loader__', '__name__', '__package__', '__spec__', 'abspath', 'copy_strip', 
'dirname', 'idleConf', 'isfile', 'join', 'python_version', 'show_idlehelp', 'tkfont']

对象 object

5个来自_sitebuiltins模块中的对象:

17. copyright()

Help on _Printer in module _sitebuiltins object:

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

>>> copyright()
Copyright (c) 2001-2022 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.

18. credits()

Help on _Printer in module _sitebuiltins object:

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

>>> credits()
    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
    for supporting Python development.  See www.python.org for more information.

44. license()

Help on _Printer in module _sitebuiltins object:

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

>>> license()
A. HISTORY OF THE SOFTWARE
==========================

Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for
National Research Initiatives (CNRI, see http://www.cnri.reston.va.us)
in Reston, Virginia where he released several versions of the
software.

In May 2000, Guido and the Python core development team moved to
BeOpen.com to form the BeOpen PythonLabs team.  In October of the same
year, the PythonLabs team moved to Digital Creations, which became
Zope Corporation.  In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization
created specifically to own Python-related Intellectual Property.
Zope Corporation was a sponsoring member of the PSF.

All Python releases are Open Source (see http://www.opensource.org for
the Open Source Definition).  Historically, most, but not all, Python
Hit Return for more, or q (and Return) to quit:  
Hit Return for more, or q (and Return) to quit: 
releases have also been GPL-compatible; the table below summarizes
the various releases.

    Release         Derived     Year        Owner       GPL-
                    from                                compatible? (1)

    0.9.0 thru 1.2              1991-1995   CWI         yes
    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes
    1.6             1.5.2       2000        CNRI        no
    2.0             1.6         2000        BeOpen.com  no
    1.6.1           1.6         2001        CNRI        yes (2)
    2.1             2.0+1.6.1   2001        PSF         no
    2.0.1           2.0+1.6.1   2001        PSF         yes
    2.1.1           2.1+2.0.1   2001        PSF         yes
    2.1.2           2.1.1       2002        PSF         yes
    2.1.3           2.1.2       2002        PSF         yes
    2.2 and above   2.1.1       2001-now    PSF         yes
Hit Return for more, or q (and Return) to quit: 

。。。略。。。

26. exit()

Help on Quitter in module _sitebuiltins object:

exit = class Quitter(builtins.object)
 |  exit(name, eof)


59. quit()

Help on Quitter in module _sitebuiltins object:

quit = class Quitter(builtins.object)
 |  quit(name, eof)


类 class

26个builtins模块的内建类,主要是各种数据类型,如整型、浮点型、复数型、字符串、枚举、切片、元组、列表、字典、集合、映射、字节数组、反向迭代器、筛选器、装饰器、range、zip、frozenset 等等。

08. 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.


10. 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 a 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


11. 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


14. 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:
 |        @classmethod
 |        def f(cls, arg1, arg2, ...):
 |            ...
 |  
 |  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.
 |  
 |  Class methods are different than C++ or Java static methods.
 |  If you want those, see the staticmethod builtin.


16. complex()

Help on class complex in module builtins:

class complex(object)
 |  complex(real=0, imag=0)
 |  
 |  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.


20. 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)


23. enumerate()

Help on class enumerate in module builtins:

class enumerate(object)
 |  enumerate(iterable, start=0)
 |  
 |  Return an enumerate object.
 |  
 |    iterable
 |      an object supporting 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]), ...


27. 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.


28. float()

Help on class float in module builtins:

class float(object)
 |  float(x=0, /)
 |  
 |  Convert a string or number to a floating point number, if possible.


30. 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.


39. int()

Help on class int in module builtins:

class int(object)
 |  int([x]) -> 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
 |  
 |  Built-in subclasses:
 |      bool


45. list()

Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.


47. 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.


49. memoryview()

Help on class memoryview in module builtins:

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


52. object()

Help on class object in module builtins:

class object
 |  The base class of the class hierarchy.
 |  
 |  When called, it accepts no arguments and returns a new featureless
 |  instance that has no instance attributes and cannot be given any.
 |  
 |  Built-in subclasses:
 |      anext_awaitable
 |      async_generator
 |      async_generator_asend
 |      async_generator_athrow
 |      ... and 89 other subclasses


58. property()

Help on class property in module builtins:

class property(object)
 |  property(fget=None, fset=None, fdel=None, doc=None)
 |  
 |  Property attribute.
 |  
 |    fget
 |      function to be used for getting an attribute value
 |    fset
 |      function to be used for setting an attribute value
 |    fdel
 |      function to be used for del'ing an attribute
 |    doc
 |      docstring
 |  
 |  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):
 |          "I am the 'x' property."
 |          return self._x
 |      @x.setter
 |      def x(self, value):
 |          self._x = value
 |      @x.deleter
 |      def x(self):
 |          del self._x


60. range()

Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).


62. reversed()

Help on class reversed in module builtins:

class reversed(object)
 |  reversed(sequence, /)
 |  
 |  Return a reverse iterator over the values of the given sequence.


64. 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.


66. 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]).


68. 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:
 |           @staticmethod
 |           def f(arg1, arg2, ...):
 |               ...
 |  
 |  It can be called either on the class (e.g. C.f()) or on an instance
 |  (e.g. C().f()). Both the class and the instance are ignored, and
 |  neither is passed implicitly as the first argument to the method.
 |  
 |  Static methods in Python are similar to those found in Java or C++.
 |  For a more advanced concept, see the classmethod builtin.


69. 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'.


71. 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)


72. tuple()

Help on class tuple in module builtins:

class tuple(object)
 |  tuple(iterable=(), /)
 |  
 |  Built-in immutable sequence.
 |  
 |  If no argument is given, the constructor returns an empty tuple.
 |  If iterable is specified the tuple is initialized from iterable's items.
 |  
 |  If the argument is a tuple, the return value is the same object.


73. type()

Help on class type in module builtins:

class type(object)
 |  type(object) -> the object's type
 |  type(name, bases, dict, **kwds) -> a new type


75. zip()

Help on class zip in module builtins:

class zip(object)
 |  zip(*iterables, strict=False) --> Yield tuples until an input is exhausted.
 |  
 |     >>> list(zip('abcdefg', range(3), range(4)))
 |     [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
 |  
 |  The zip object yields n-length tuples, where n is the number of iterables
 |  passed as positional arguments to zip().  The i-th element in every tuple
 |  comes from the i-th iterable argument to zip().  This continues until the
 |  shortest argument is exhausted.
 |  
 |  If strict is true and one of the arguments is exhausted before the others,
 |  raise a ValueError.


内置函数 built-in function

真正的的内置函数有42个,除了open()来自io模块,其它都是builtins模块中的函数。

01. abs()

Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.


02. aiter()

Help on built-in function aiter in module builtins:

aiter(async_iterable, /)
    Return an AsyncIterator for an AsyncIterable object.


03. all()

Help on built-in function all in module builtins:

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


04. anext()

Help on built-in function anext in module builtins:

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


05. any()

Help on built-in function any in module builtins:

any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.


06. ascii()

Help on built-in function ascii in module builtins:

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.


07. bin()

Help on built-in function bin in module builtins:

bin(number, /)
    Return the binary representation of an integer.
    
    >>> bin(2796202)
    '0b1010101010101010101010'


09. breakpoint()

Help on built-in function breakpoint in module builtins:

breakpoint(...)
    breakpoint(*args, **kws)
    
    Call sys.breakpointhook(*args, **kws).  sys.breakpointhook() must accept
    whatever arguments are passed.
    
    By default, this drops you into the pdb debugger.


12. callable()

Help on built-in function callable in module builtins:

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.


13. chr()

Help on built-in function chr in module builtins:

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


15. compile()

Help on built-in function compile in module builtins:

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-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.


19. delattr()

Help on built-in function delattr in module builtins:

delattr(obj, name, /)
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''


21. dir()

Help on built-in function dir in module builtins:

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.


22. divmod()

Help on built-in function divmod in module builtins:

divmod(x, y, /)
    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.


24. eval()

Help on built-in function eval in module builtins:

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.


25. exec()

Help on built-in function exec in module builtins:

exec(source, globals=None, locals=None, /, *, closure=None)
    Execute the given source in the context of globals and locals.
    
    The source may be a string representing one or more Python statements
    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.
    The closure must be a tuple of cellvars, and can only be used
    when source is a code object requiring exactly that many cellvars.


31. 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.


32. globals()

Help on built-in function globals in module builtins:

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.


33. hasattr()

Help on built-in function hasattr in module builtins:

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.


34. hash()

Help on built-in function hash in module builtins:

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.


36. hex()

Help on built-in function hex in module builtins:

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


37. id()

Help on built-in function id in module builtins:

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.)


38. input()

Help on built-in function input in module builtins:

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.


40. isinstance()

Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.
    
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.


41. issubclass()

Help on built-in function issubclass in module builtins:

issubclass(cls, class_or_tuple, /)
    Return whether 'cls' is 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 ...``.


42. 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.


43. len()

Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.


46. locals()

Help on built-in function locals in module builtins:

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.


48. max()

Help on built-in function max in module builtins:

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.


50. min()

Help on built-in function min in module builtins:

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


51. 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.


53. oct()

Help on built-in function oct in module builtins:

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


54. open()

Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError 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)


55. ord()

Help on built-in function ord in module builtins:

ord(c, /)
    Return the Unicode code point for a one-character string.


56. pow()

Help on built-in function pow in module builtins:

pow(base, exp, mod=None)
    Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
    
    Some types, such as ints, are able to use a more efficient algorithm when
    invoked using the three argument form.


57. print()

Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    
    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.


61. repr()

Help on built-in function repr in module builtins:

repr(obj, /)
    Return the canonical string representation of the object.
    
    For many object types, including most builtins, eval(repr(obj)) == obj.


63. round()

Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.
    
    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.


65. setattr()

Help on built-in function setattr in module builtins:

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''


67. sorted()

Help on built-in function sorted in module builtins:

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 customize the sort order, and the
    reverse flag can be set to request the result in descending order.


70. sum()

Help on built-in function sum in module builtins:

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.


74. 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__.


功能分类

这42个内置函数从使用功能上可以分为12大类:

数学运算

01-abs()
22-divmod()
48-max()
50-min()    
56-pow() 
63-round()
70-sum()

逻辑运算

03-all()
05-any()

输入输出

38-input()
57-print()

进制转换

07-bin()
36-hex() 
53-otc()

类型转换

06-ascii()
13-chr()
55-ord()
61-repr()

迭代器

02-aiter()
04-anext()
42-iter()
51-next()

文件操作

54-open()

排序操作

67-sorted()

代码执行

09-breakpoint()
15-compile()
24-eval()
25-exec()

对象属性

12-callable()
21-dir()
34-hash()
40-isinstance()
41-issubclass()
43-len()

属性操作

19-delattr()
31-getattr()
33-hasattr()
65-setattr()

变量和作用域

32-globals()
37-id()
46-locals()
74-vars()


小结

Python的内置函数有75个,要么说42个或者说70个(5个对象类的不算);再不要说只有68个了,这个“68个”的版本说是截止到python版本3.6.2,并且对象类的5个没算进去。这样相比较,其实也就新增了3个函数,分别是:
Python3.7新增了09-breakpoint();
Python3.10新增了02-aiter()和04-anext()。

Python 内置函数详解 (4) 类型转换 阅读详情

相关推荐

Python 内置函数详解 (1) 数学运算

Python 内置函数详解 (1) 数学运算

汉阳Hann's Home 632

python基础-day11-模块化

python基础-day11-模块化

weixin_42856170的博客 240

Greenplum基础

CREATE DATABASE 是 SQL 命令,用于创建一个新的数据库。name 是你要创建的数据库的名称。这个名称是必须的,并且在同一个数据库服务器上必须是唯一的。可选项,OWNER 指定了新数据库的所有者,如果未指定,新数据库的所有者默认是执行该命令的用户。dbowner 是数据库所有者的用户名。可选项,TEMPLATE 指定了用于创建新数据库的模板。在 PostgreSQL 和 GreenPlum 中,通常有一个名为 template1 的默认模板。如果不指定,就会使用这个默认模板。

m0_57697768的博客 1210

【py code everyday line 2】2023-02-24

今天开始在使用eng版来学习 line two 的课程 先来做个复习 而且计划直接使用3rd来学习,let’s go 现在发现英文读起来很舒服,而且不用英文来学习,用中文生硬的来背诵,是比较无效的学习 We create a list called squares to hold the data that we’ll plot. Then we follow another common Matplotlib convention by calling the subplots() function .

JMHSMX的博客 163

零代码实战:基于Coze平台打造测试用例生成AI助手

本文详细介绍了如何利用Coze平台零代码打造测试用例生成AI助手,通过智能体和工作流配置,实现需求文档自动解析与结构化测试用例生成。该方案显著提升测试效率,特别适合敏捷开发中频繁变更的需求场景,帮助测试工程师快速应对挑战。

weixin_42526015的博客 210

R语言dplyr包recode函数、recode_factor函数数值或因子替换实战

R语言dplyr包recode函数、recode_factor函数数值或因子替换实战 目录 R语言dplyr包recode函数、recode_factor函数数值或因子替换实战 #导入dplyr包 #recode函数进行数值替换 #recode_factor函数对因子变量进行替换 #导入dplyr包 install.packages("dplyr") # Install & load dplyr library("dpl.

data+scenario+science+insight 1592

2025最新版Python 3.13.5安装使用指南

摘要:本文全面介绍了Python的发展历程。文章详细讲解了Python 3.13.5在macOS系统上的下载安装步骤,包括软件包获取、安装向导操作、SSL证书配置等关键环节。同时提供了Python环境验证方法、首个"Hello World"程序示例,以及IDLE开发环境的使用说明。最后介绍了如何查阅本地文档和安装第三方库。

jackson_lingua的博客 3853

【微服务】Spring Aop原理深入解析

spring原理深度解析

congge 1万+

Python更新

更新方式:采用安装包进行更新。

JSHS_123456的博客 2万+

SY6982C 7.4V锂电池1A充电模块原理图设计,已量产

在手持设备、便携工具与小型无人机等场景中,7.4V(2S)锂聚合物电池的应用愈发广泛。这类电池对充电系统的安全性、效率与兼容性提出了明确要求:需支持 USB 5V 输入、1A 安全充电,同时具备多重保护机制。本文将结合一款基于 SY6982C 的充电原理图,深入解析其电路设计与技术亮点。

不脱发的程序猿 376

python爬虫:采集求职者简历信息并进行人才分析

通过 Python 爬虫抓取求职者简历信息并进行人才分析,可以帮助企业快速筛选和匹配人才。但在实施过程中,必须严格遵守法律法规,确保数据来源合法合规。如果需要更复杂的分析,可以结合自然语言处理(NLP)和机器学习技术,进一步挖掘数据价值。

数据知道的博客 1万+

【python基础】windows下python环境版本更新教程

本篇文章主要讲解python旧版本更新新版本的方法和说明适用人群:python新手python更新共有两种常见的方法:一是可以通过命令行【linux服务器、mac、win系统】、二是可以通过重新安装【windows、mac、linux图形化系统中】进行更新,

m0_59162248的博客 1万+

SAP_PP模块跑完 MRP,MD04 里却看不到“计划订单”?排查这 3 个最容易被忽略的主数据参数

MRP 是 SAP 逻辑最严密的模块之一,它绝不会随机罢工。当 MD04 里看不到计划订单时,请不要怀疑系统的计算能力。99% 的情况,都是因为我们给系统下达了矛盾的指令:一边告诉它“我有需求”,一边却通过主数据告诉它“不要计划”、“不要触发”或者“我是冻结的”。掌握这 3 个排查点,你就能在 5 分钟内解决大部分“MRP 失灵”的悬案,成为用户眼中的“系统神医”。

我小时候很黑的博客 615

2024年最全Python 新版本有75个内置函数,你不会不知道吧

网上多流传68个内置函数,不管是68还75都对,因为所在版本不一样。但是新版本3.11已经有75个内置函数,再说“python有68个内置函数,你不会不知道吧”就有点落后了。68一说的版本中把__import__也算进去,它可以在一行内导入库并引入库函数,把这加进去说成有76个的版本也是可以的。关于__import__的用法,例如:导入sys标准库,查询我的python版本号:‘3.11’等价于:import syssys.winver‘3.11’

2401_84584522的博客 255

利用蓝牙低功耗技术与位置数据,提升邮政运输工具及笼车追踪的效率

BLE 即蓝牙低功耗技术,与无线音箱或各类电脑配件所用的技术类似。正如其名,BLE 的特点是:在实现相近传输范围的同时,功耗显著更低。这让它能应用于对电池续航要求极高的场景。

专业开发者的博客,一个从事Android WiFi和蓝牙的工程师 780

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Python 新版本有75个内置函数,你不会不知道吧(1)

别在网上瞎学了,我最近也做了一些资源的更新,只要你是我的粉丝,这期福利你都可拿走。我先来介绍一下这些东西怎么用,文末抱走。这是我花了几天的时间去把Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。最近我才对这些路线做了一下新的更新,知识体系更全面了。

m0_60721649的博客 706

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

2024年最新15个经典面试问题薪资,Python 新版本有75个内置函数,你不会不知道吧,2024年最新面试进阶100题网盘

网上多流传68个内置函数,不管是68还75都对,因为所在版本不一样。但是新版本3.11已经有75个内置函数,再说“python有68个内置函数,你不会不知道吧”就有点落后了。68一说的版本中把__import__也算进去,它可以在一行内导入库并引入库函数,把这加进去说成有76个的版本也是可以的。关于__import__的用法,例如:导入sys标准库,查询我的python版本号:‘3.11’等价于:import syssys.winver‘3.11’

2401_84132423的博客 523

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

不会吧,不会吧,不会还有人不知道Python给图片加水印超级简单哦

不会吧,不会吧,不会还有人不知道❤️Python给图片加水印❤️超级简单哦 文章目录不会吧,不会吧,不会还有人不知道❤️Python给图片加水印❤️超级简单哦介绍安装模块进行添加水印的操作结果的展示: 介绍 我们的图片的版权在有的时候也是十分重要的哦,因此这就需要来给我们的图片去加上水印,当今也确实是有很多的给图片加水印的软件之类的东西的,但是,也许有人还不知道,Python也可以给图片加水印,而且效果良好、操作方便快捷简便。 使用Python进行添加水印可以实现完全按照自己的想法来进行水印的添加,可以自己

江月的博客 1万+

对比测试:75KXCC新版本开发效率提升报告

最近团队在评估75KXCC新版本的性能改进,为了更客观地量化效率提升效果,我尝试开发了一个自动化测试工具。这个工具不仅能对比新旧版本的差异,还能生成可视化报表,帮助团队直观理解优化效果。下面分享具体实现思路和测试结果。进行原型开发时,其开箱即用的Python环境和可视化部署功能大大缩短了调试周期,特别是需要快速验证想法时,不用折腾环境配置就能看到实时结果,对效率工具的开发效率提升帮助很大。前端设计了三层数据展示:总览仪表盘显示核心KPI对比,趋势图呈现历史数据变化,详情表格展示每个测试用例的原始数据。

SilverfoxOwl19的博客 1416

Python 内置函数 61-75

61、hash(): hash() 用于获取取一个对象(字符串或者数值等)的哈希值。 hash() 函数可以应用于数字、字符串和对象,不能直接应用于 list、set、dictionary。 在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。 hash() 函数的对象字符不管有多长,返回的 hash 值都是固定长度的,也用于校验程序在传输过程中是否被第三方(木马)修改,如果程序(字符)在传输过程中被修改hash值即发生变化,如果没有被修改,则 hash

qq_43518274的博客 257

python的内置函数

python-内置函数 内置函数操作 1 #!usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # 1.locals()和globals() 4 # def func(): 5 # x=1 6 # y=2 7 # print(locals()) 8 # ...

Aiden的博客 219

对你大有助益的22个Python内置函数

Python中的函数就是内置函数。目前最新版本中一共有75个内置函数,这里梳理了其中最常用、最精华的22个。

Trb401012的博客 1036

Python 常用内置函数

Python 中共有75个内置函数,这些是 Python 自带的函数,在需要使用时可以直接调用。

小嗷犬的博客 518

python一共有多少个内置函数_Python 35个内置函数,你都ok吗?

Python一共有60多个内置函数,今天先梳理其中35 个1 abs()绝对值或复数的模In [1]: abs(-6)Out[1]: 6。2 all()接受一个迭代器,如果迭代器的所有元素都为真,那么返回True,否则返回FalseIn [2]: all([1,0,3,6])Out[2]: FalseIn [3]: all([1,2,3])Out[3]: True3 any()接受一个迭代器,如果...

weixin_39704727的博客 1060
上一篇: Linux 终端命令之文件目录操作,对比Dos相关命令
下一篇: Python 内置函数详解 (1) 数学运算
Hann Yang
Hann Yang 优质创作者: 编程框架技术领域 优质创作者: 编程框架技术领域 领域专家: 算法与数据结构技术领域 领域专家: 算法与数据结构技术领域
博客等级 码龄19年 4万+粉丝 1041原创
评论 100
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值