Python3 内建函数总结(-)
发布时间:2017-11-23T14:42:03:手机请访问
查看 Python3
下的内建函数:
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
#
bin(x) 以字符串形式返回整数x的二进制的表示
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
1 2 3 |
bytearray() 函数
返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。可以通过“字节与字节数组操作”章节来查看相关字节数组的内容。下面说明一下几种特别的使用方法: 1. 如果source是一个字符串,那么必须给出endcoding是什么样编码的,以便转换为合适的字节保存。 2. 如果source是一个整数,那么这个数组将初始化为空字节。 3. 如果source是一个有缓冲区接口的对象,那么只读的接口初始到数组里。 4. 如果source是一个迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里。 如果没有输入任何参数,默认就是初始化数组为0个元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#bytearray()函数 a = bytearray('1234深圳', 'utf-8') print(a) b = bytearray() print(b) c = [1,4,5,7,8] print(bytearray(c)) ###output### ➜ d2 python3 c2.py bytearray(b'1234\xe6\xb7\xb1\xe5\x9c\xb3') bytearray(b'') bytearray(b'\x01\x04\x05\x07\x08') |
callable() 函数
callable() 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。
对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。
1 2 3 4 5 |
def demo(): pass print(callable(demo)) #output True |
Python3 classmethod函数
classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。也就是类方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class A(object): name ="a" @classmethod def print_a(cls): print(cls.name) def main(): A.print_a() if __name__ == '__main__': main() ###output### a |
Python3 compile()
Python3 delattr() 函数
delattr 函数用于删除属性。
delattr(x, 'foobar') 相等于 del x.foobar。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#!/usr/bin/python # -*- coding: UTF-8 -*- class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ',point1.x) print('y = ',point1.y) print('z = ',point1.z) delattr(Coordinate, 'z') print('--删除 z 属性后--') print('x = ',point1.x) print('y = ',point1.y) # 触发错误 print('z = ',point1.z) |
输出结果:

Python3 frozenset() 函数
frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素
class frozenset([iterable])
iterable -- 可迭代的对象,比如列表、字典、元组等等。
返回新的 frozenset 对象,如果不提供任何参数,默认会生成空集合。。
1 2 3 4 5 6 7 |
>>>a = frozenset(range(10)) # 生成一个新的不可变集合 >>> a frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> b = frozenset('runoob') >>> b frozenset(['b', 'r', 'u', 'o', 'n']) # 创建不可变集合 >>> |
Python3 getattr() 函数
1 2 3 4 5 6 7 8 9 10 11 12 |
class B(object): bar = 1 def demo(self): print("demo") def main(): b = B() print(getattr(b,'bar')) print(getattr(b,'bar2')) if __name__ == '__main__': main() |

Python3 globals() 函数
globals() 函数会以字典类型返回当前位置的全部全局变量
1 2 |
>>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 'helloword'} |
Python3 hash() 函数

hash() 用于获取取一个对象(字符串或者数值等)的哈希值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
In [17]: hash('songhao') Out[17]: -3120864605816462735 In [18]: hash('songhao') Out[18]: -3120864605816462735 In [19]: hash('songhaow') Out[19]: -8446351638320504046 In [20]: hash('test') Out[20]: 7392172603845907021 In [21]: hash("函数会以字典类型返回当前位置的全部全局变量") Out[21]: -7195658508907698296 |
