参考博客地址:https://www.cnblogs.com/sesshoumaru/p/6140987.html#p2

人生三问

什么是内置函数
  内置函数就是python解释器给我们已经定义好的一系列函数,我们可以直接进行调用,而不必进行定义的。 为什么要用内置函数
  对于一些常用的功能,我们没有必要重新去一个一个的实现,因为有人已经帮我们实现了,我们只需要进行调用就可以了。提高我们的开发效率 怎么使用内置函数
  就和我们自定义的函数使用方法是一样的,通过函数名加括号就可以了。
  例如:max()

未完待续:

  5. 装饰器(3个)待定

  10. 反射操作(8个)(待定)

  super object(待定)

  memoryview

python的内置函数(总共68个)

 第11天内置函数详解-LMLPHP

1.   常用的   max, min, sorted,map, filter, reduce

参考博客: https://www.cnblogs.com/huwentao/p/9766004.html

2. 文件操作(1个)

open函数

常用的:
f = open('a.txt', 'rt', encoding='utf-8')
f.read()

3. 交互操作(2个)

input
  res = input('>>>')
print
  print(res, end='=?')

4. 变量操作(2个)

globals  返回当前作用域内的全局变量和其值组成的字典
locals   返回当前作用域内的局部变量和其值组成的字典

print(globals())
print(locals())

5. 装饰器(3个)待定

property() 标示属性的装饰器
staticmethod()  标示方法为静态方法的装饰器
classmethod()  标示方法为类方法的装饰器

6. 编译执行(4个)

compile  将字符串编译为代码,使得返回值能够被exec来执行或者eval来求值
eval   执行动态表达式来求值
  eval('1+2+3')
exec 执行动态语句块
  exec('a = 1')
  a
repr 返回一个对象的字符串表示形式
第11天内置函数详解-LMLPHP第11天内置函数详解-LMLPHP
# compile 需要三个参数
# source: 需要执行的代码段
# filename: 从文件读取需要编译的代码, 如果有source,filename传递一个空字符串即可
# mode:执行模式,exec执行流程语句,eval简单的求值表达式,single交互式语句

# 例一:exec执行流程语句,没有返回值
source = '''
for i in range(10):
    print(i)
'''
res = compile(source, '', mode='exec')
print(exec(res))


# 例一:eval执行简单的一些求值表达式,返回值
source = '''1+2+3+4'''
res = compile(source, '', mode='eval')
print(eval(res))


# 例三: exec执行交互式命令
source = '''
name = input('>>').strip()
'''
res = compile(source, '', mode='single')
exec(res)
complie,eval, exec使用方法

repr: 返回一个对象的字符串表现形式,大部分和str是类似的,只是当他转化一个字符串的时候会存在差异。如下:

第11天内置函数详解-LMLPHP

7. 数学运算(7个)

abs     绝对值
  abs(-1) ====》 1 max   最大值
  max([1,2 ,3]) =====》 3 min 最小值
  min([1,2,3 ]) =====》 1 sum   和
  sum([1,2 ,3 ])======》 6
divmod 返回两个数值的商和余数
power 返回幂运算值或者与其指定的数值的模
round 对浮点数进行四舍五入取值
print(max([1,2,3]))   # 1
print(min([1,2,3]))   # 2
print(sum([1,2,3]))  # 6

print(divmod(5, 2))    # (2, 1)
print(pow(2, 3, 5))  # =====》 2 ** 3 % 5 结果为3
print(round(1.5))  # ====> 2

8.对象操作(7个)

dir    返回对象或者当前作用域内的属性列表
ascii  返回对象的可打印表字符串表现方式
vars  返回当前作用域内的局部变量和其值组成的字典,或者返回对象的属性列表
format 格式化输出字符串
help   返回对象的帮助信息
id     返回对象的唯一标识符
type   返回对象的类型
hash   返回对象的hash值
len    返回对象的长度 

dir 

>>> dir()    # 显示当前作用域内的属性列表
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']
>>> globals().keys()  # 全局作用域的属性key
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'a'])
>>> import math
>>> dir(math)   # 显示的是当前对象math所具有的属性,也就是它的方法
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>>

 

ascii和之前说的repr是一样的只是在出现中文的时候表现形式不一样的额

>>>
>>> repr('中国')
"'中国'"
>>> ascii('中国')
"'\\u4e2d\\u56fd'"
>>> repr('hello')
"'hello'"
>>> ascii('hello')
"'hello'"
>>>

id, type, hash, len, help

>>> id('hello')  # 返回当前对象的唯一标示符,也也就是它的地址
9883616
>>> type('hello')   # 返回当前对象的类型
<class 'str'>
>>> hash('hello')  # 返回一个hash值
73169866
>>> len('hello')  # 返回对象的长度
5
>>> help(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'.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __eq__(self, value, /)
 |      Return self==value.

vars  

(1) 当函数不接收参数时,其功能和locals函数一样,返回当前作用域内的局部变量。

>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': [1, 2, 3], 'math': <module 'math' (built-in)>}
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': [1, 2, 3], 'math': <module 'math' (built-in)>}
>>>

(2)当函数接收一个参数时,参数可以是模块、类、类实例,或者定义了__dict__属性的对象。返回的是当前的属性和dir一样,只是vars返回的是字典

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> vars(dict).keys()
dict_keys(['__repr__', '__hash__', '__getattribute__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__init__', '__len__', '__getitem__', '__setitem__', '__delitem__', '__contains__', '__new__', '__sizeof__', 'get', 'setdefault', 'pop', 'popitem', 'keys', 'items', 'values', 'update', 'fromkeys', 'clear', 'copy', '__doc__'])
>>>

format在字典阶段已经介绍过了,这里不再赘述

9. 序列操作(8个)

all   判断可迭代对象每个元素是否都是True
any  判断可迭代对象中是否又True的元素
zip   聚合传入的每个迭代器中的相同位置的元素,返回一个新的元祖类型迭代器
reversed   反转序列生成新的可迭代对象
next    返回迭代器对象中的下一个元素值

filter 过滤 map 映射 sorted 排序

all

>>> all([])  # 首先空的可迭代对象返回的是True
True
>>> all([1,2 ,3])   #  判断里面的值是不是都是True
True
>>> all([1,2 ,0])
False
>>> all([1,2 ,''])
False

any 

>>> any([])    # 可迭代对象为空的时候any返回为False
False
>>> any([1,2,3])   # 可迭代对象中只要又True就返回True
True
>>> any(['', 0])
False
>>> any(['', 1])
True
>>>

zip

>>> zip([1,2 ,3], (4, 5,6))   # 组合两个可迭代对象的值
<zip object at 0x009C2260>
>>> a = zip([1,2 ,3], (4, 5,6))
>>> list(a)
[(1, 4), (2, 5), (3, 6)]
>>>

reversed

>>> list(reversed('hello  world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ' ', 'o', 'l', 'l', 'e', 'h']
>>> reversed('hello world!')
<reversed object at 0x00980D70>
>>>

next返回迭代器下一个元素,就是调用__next__方法

>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'

filter, map, reduce 在文章开头已经给了地址

10. 反射操作(8个)(待定)

hasattr
getattr
setattr
delattr
callable
isinstance
issubclass
__import__

11. 类型转换(24个)

bytearray    根据传入的参数创建一个新的字节数组
bytes 根据传入的参数创建一个新的不可变字节数组 memoryview 根据传入的参数创建一个新的内存查看对象 frozenset 根据传入的参数创建一个新的不可变集合
enumerate 根据可迭代对象创建枚举对象 slice 根据传入的参数创建一个切片对象 super 根据传入的参数创建一个新的子类和父类的关系的代理对象 object 创建一个新的object对象
iter 根据传入的参数创建一个新的可迭代对象 range

ord chr

# 二进制八进制和十六进制 bin 二进制 hex 十六进制 oct 八进制 # 数据类型 bool int float complax str tuple list dict set

bytearray

>>>
>>> len(bytearray())  # 如果不传值,返回的是一个长度为0的字节数组
0
>>> b = bytearray('中国', encoding='utf-8')  # 其实就是把传递进来的字符串编码成了utf-8的形式
>>> len(b)
6
>>> bytearray('中国', encoding='utf-8')
bytearray(b'\xe4\xb8\xad\xe5\x9b\xbd')
>>>

bytes   其实和bytearray是一样的,只是在创建的过程中bytes是不可修改的

>>> b = bytes(10)
>>> b
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> b[0]
0
>>> b[1] = 1 #不可修改
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    b[1] = 1
TypeError: 'bytes' object does not support item assignment

>>> b = bytearray(10)
>>> b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> b[1] = 1 #可修改
>>> b
bytearray(b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00')

memoryview 返回一个内存查看对象(没搞懂)

>>> b = memoryview(b'abcd')   # 获得一个内存对象
>>> b
<memory at 0x008568B8>
>>> b[1]    # 可以通过索引去查看当前位置所对应的值
98
>>> b[-1]
100
>>> b[1:2]
<memory at 0x008562A0>
>>>

frozenset

>>> a = frozenset(range(10))  # 创建了一个不可变集合
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
>>> a.add(2)   # 创建的集合是不能够改变的
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>

enumerate

>>> seasons = ['spring', 'summer', 'Fall', 'Winter']
>>> b = enumerate(seasons)   # 默认是从0开始一一对应列表中的值
>>> list(b)
[(0, 'spring'), (1, 'summer'), (2, 'Fall'), (3, 'Winter')]
>>> b = enumerate(seasons, start=1)  # 可以通过start去指定开始的值
>>> list(b)
[(1, 'spring'), (2, 'summer'), (3, 'Fall'), (4, 'Winter')]
>>>

slice 

>>> b = list(range(10))
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> c = slice(5)   # 定义一个切片的规则,然后通过下面去调用
>>> b[c]
[0, 1, 2, 3, 4]
>>> c = slice(1,5)
>>> b[c]
[1, 2, 3, 4]
>>> c = slice(1,5, 2)
>>> b[c]
[1, 3]
>>>

super object(待定)

iter

>>> a = iter([1,2,3])   # 创建一个可迭代对象
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

range

>>> list(range(0))  # 结束的值小于等于0的时候会返回一个空字符串
[]
>>> list(range(-1))
[]
>>> list(range(1, 10, -2))
[]
>>> list(range(1, 10, 2))  # 第三个数是步长,默认是一
[1, 3, 5, 7, 9]
>>>

ord , chr

>>> ord('a')   # unicode字符对应的整数
97
>>> chr(97)   # 整数对应的unicode字符
'a'
>>> ord('')
20013
>>> ord('20013')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 5 found
>>> chr(20013)
''
>>>
10-14 16:31