python内建函数是什么_Python内建函数

本文内容参考多篇博客文章及Python官方文档。

在python中,输入help(dir(__builtins__))可以查看python内建函数。python中所有的内建函数如下:

>>>help(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', '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', 'WindowsError', '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']

在此,对常用内建函数做一下简单了解。

abs() 返回绝对值

>>>abs(-1)

1

callable() 函数是否可以调用

>>>callable(abs)

True

all(iterable) iterable元素都不为False、''、0或者iterable为空,则all(iterable)为True,也就是说只要iterable元素有一个为"假",则为False。当iterable为空时也返回Ture。

>>>all([])

True

>>>all([1,2,3])

True

>>>all([0,1,2,3]) #非0为真,故返回False

False

any(iterable) iterable的任何元素都为False、0,'',或者iterable全为空,则any(iterable)为False,也就是说所有的iterable都为'假',则any(iterable)为False。也即"全‘假’为False,有‘真’为True。

>>>any(0,"a",[])

True

>>>any(0,[],"")

False

bool() 返回一个布尔值,TrueorFalse

chr() chr()函数用一个范围在range(256)内的整数作参数,返回一个对应的unicode字符。

ord() ord()函数是chr()函数的配对函数,它以一个unicode字符(长度为1的字符串)作为参数,返回对应的Unicode数值。

>>>chr(65)

A

>>>ord(A)

65

Python基本数据类型包括int,str,float,complex(复数)

divmod(a,b) 将a除以b的商和余数以一个元祖的形式返回

>>>divmod(17,3)

(5,2)

enumerate(iterable[,start]) 返回一个iterable元素以及其索引

>>>a=list(enumerate(list(range(5))))

>>>print(a)

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

eval() 可以用来将字符串str当成有效Python表达式来求值,并返回计算结果。

exec()语句可以将:1.代码字符串 2.文件对象 3.代码对象 4.tuple 当作代码来执行。

>>>eval("print("hello wrld!")")

hello wrld!

>>>exac("a=1")

>>>a

1

format 格式化输出函数

>>>a="hello "

>>>b="world!"

>>>print("{}{}".format(a,b))

hello world!

frozenset set和frozenset皆为无序不含重复序列集合。set和frozenset最本质的区别是前者是可变的、**后者是不可变的 **。当集合对象会被改变时(例如添加、删除元素等),只能使用set ,一般来说使用fronzet的地方都可以使用set 。

因此set不支持index方法,但支持len(set),x in set,add(),remove() 等方法。

getattr,hasattr,setattr,delattr是与class属性相关的一类函数。

locals,globals是与变量命名空间相关的一些函数,locals表示局部变量,globas表示全局变量。

>>> def test(arg):

#函数 foo 在它的局部名字空间中有两个变量:arg(它的值被传入函数),和 z(它是在函数里定义的)。

z = 1

print locals()

>>> test(4)

#locals 返回一个名字/值对的字典。这个字典的键字是字符串形式的变量名字,字典的值是变量的实际值。

#所以用 4 来调用 foo,会打印出包含函数两个局部变量的字典:arg (4) 和 z (1)。

{'z': 1, 'arg': 4}

>>> test('doulaixuexi')

#locals 可以用于所有类型的变量。

{'z': 1, 'arg': 'doulaixuexi'}

>>>a=1

>>>print(globals()) # 打印全局变量

{'__builtins__': , '__spec__': None, '__cached__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x01EF5930>, '__file__': 'D:\\PY sumbline coding\\just for test.py', '__package__': None,

'__name__': '__main__', 'a': 1, '__doc__': None}

hex 返回一个数的十六进制形式。

>>>hex(1)

0x1

id 返回变量的内存地址,相当于C中的指针

>>>a=15

>>>id(a)

1590319600

iter 对于string、list、dict、tuple等这类容器对象,使用for循环遍历是很方便的。在后台for语句对容器对象调用iter()函数,iter()是python的内置函数。iter()会返回一个定义了next()方法的迭代器对象,它在容器中逐个访问容器内元素,next()也是python的内置函数。在没有后续元素时,next()会抛出一个StopIteration异常,通知for语句循环结束。比如:

>>> s = 'abc'

>>> it = iter(s)

>>> it

>>> next(it)

'a'

>>> next(it)

'b'

>>> next(it)

'c'

>>> next(it)

Traceback (most recent call last):

File "", line 1, in

StopIteration

max(),min()返回一个 iterable对象或多个参数中的最大值。

>>>max([1,2,3])

3

>>>min(1,2,3)

1

len() 返回容器中元素的数量

pow(x,y) 属于math模块,相当于x**y

repr repr()函数与str()函数用法基本一样,返回一个符合标准规范的string,只是repr()对Python更友好,而str()读用户更友好。

round(number,[ndigits]) 对number进行四舍五入,ndigits表示保留位数,若为负数中表示对整数进行四舍五入

>>>round(5.786,2)

5.79

>>round(146875, -2)

146900

reversed() 将序列进行反向

>>>a=list(range(5))

>>>a.reversed()

[4,3,2,1,0]

sorted(iterable, key=None, reverse=False) 返回经过排序的iterable,sorted()并不改变原iterable。

sort()是list的一种排序方法,会改变原来的list。

>>>a=list(range(5))

>>>sorted(a,reverse=True)

>>>a

[0,1,2,3,4]

>>>b=sorted(a,reverse=True)

>>>b

[4,3,2,1,0]

>>>b.sort()

>>>b

[0,1,2,3,4]

sum(iterable[,start]) 对iterable进行求和,只能对数字进行求和,不能对字符串求和。

>>>sum(list(range(5)))

10

super() 继承,暂时还不理解。。。以后再写。。。

zip(iter1 [,iter2 [...]]) 返回一个配对的对象,以长度最短的iter为准,短iter配对完即停止配对。常用于建字典,此时参数只能有两个。

>>>a=list(range(10))

>>>b=list(range(5))

>>>c=dict(zip(a,b))

>>>print(c)

{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}

此外,Python基本数据结构string,list,set,dictionary,tuple以及3个高级函数,map(),reduce(),filter()将分两个章节写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值