经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
第11天内置函数详解
来源:cnblogs  作者:沉沦的罚  时间:2018/10/15 9:26:05  对本文有异议

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

人生三问

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

 

未完待续:

  1.   5. 装饰器(3个)待定
  2.   10. 反射操作(8个)(待定)
  3.   super object(待定)
  4.   memoryview

 

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

 

 

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

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

2. 文件操作(1个)

  1. open函数
  2. 常用的:
  3. f = open('a.txt', 'rt', encoding='utf-8')
  4. f.read()

3. 交互操作(2个)

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

4. 变量操作(2个)

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

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

5. 装饰器(3个)待定

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

6. 编译执行(4个)

  1. compile 将字符串编译为代码,使得返回值能够被exec来执行或者eval来求值
  2. eval 执行动态表达式来求值
      eval('1+2+3')
  3. exec 执行动态语句块
      exec('a = 1')
      a
    repr 返回一个对象的字符串表示形式
  1. # compile 需要三个参数
  2. # source: 需要执行的代码段
  3. # filename: 从文件读取需要编译的代码, 如果有source,filename传递一个空字符串即可
  4. # mode:执行模式,exec执行流程语句,eval简单的求值表达式,single交互式语句
  5.  
  6. # 例一:exec执行流程语句,没有返回值
  7. source = '''
  8. for i in range(10):
  9. print(i)
  10. '''
  11. res = compile(source, '', mode='exec')
  12. print(exec(res))
  13. # 例一:eval执行简单的一些求值表达式,返回值
  14. source = '''1+2+3+4'''
  15. res = compile(source, '', mode='eval')
  16. print(eval(res))
  17. # 例三: exec执行交互式命令
  18. source = '''
  19. name = input('>>').strip()
  20. '''
  21. res = compile(source, '', mode='single')
  22. exec(res)
complie,eval, exec使用方法

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

7. 数学运算(7个)

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

 

  1. print(max([1,2,3])) # 1
  2. print(min([1,2,3])) # 2
  3. print(sum([1,2,3])) # 6
  4.  
  5. print(divmod(5, 2)) # (2, 1)
  6. print(pow(2, 3, 5)) # =====》 2 ** 3 % 5 结果为3
  7. print(round(1.5)) # ====> 2

8.对象操作(7个)

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

 

dir 

  1. >>> dir() # 显示当前作用域内的属性列表
  2. ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']
  3. >>> globals().keys() # 全局作用域的属性key
  4. dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'a'])
  5. >>> import math
  6. >>> dir(math) # 显示的是当前对象math所具有的属性,也就是它的方法
  7. ['__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']
  8. >>>

 

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

  1. >>>
  2. >>> repr('中国')
  3. "'中国'"
  4. >>> ascii('中国')
  5. "'\\u4e2d\\u56fd'"
  6. >>> repr('hello')
  7. "'hello'"
  8. >>> ascii('hello')
  9. "'hello'"
  10. >>>

 

id, type, hash, len, help

  1. >>> id('hello') # 返回当前对象的唯一标示符,也也就是它的地址
  2. 9883616
  3. >>> type('hello') # 返回当前对象的类型
  4. <class 'str'>
  5. >>> hash('hello') # 返回一个hash值
  6. 73169866
  7. >>> len('hello') # 返回对象的长度
  8. 5
  9. >>> help(str) # 返回当前对象的帮助信息
  10. Help on class str in module builtins:
  11. class str(object)
  12. | str(object='') -> str
  13. | str(bytes_or_buffer[, encoding[, errors]]) -> str
  14. |
  15. | Create a new string object from the given object. If encoding or
  16. | errors is specified, then the object must expose a data buffer
  17. | that will be decoded using the given encoding and error handler.
  18. | Otherwise, returns the result of object.__str__() (if defined)
  19. | or repr(object).
  20. | encoding defaults to sys.getdefaultencoding().
  21. | errors defaults to 'strict'.
  22. |
  23. | Methods defined here:
  24. |
  25. | __add__(self, value, /)
  26. | Return self+value.
  27. |
  28. | __contains__(self, key, /)
  29. | Return key in self.
  30. |
  31. | __eq__(self, value, /)
  32. | Return self==value.

 

vars  

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

  1. >>> vars()
  2. {'__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)>}
  3. >>> locals()
  4. {'__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)>}
  5. >>>

 

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

  1. >>> dir(dict)
  2. ['__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']
  3. >>> vars(dict).keys()
  4. 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__'])
  5. >>>

 

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

 

9. 序列操作(8个)

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

    filter 过滤
  6. map 映射
  7. sorted 排序

 

all

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

 

any 

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

 

zip

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

 

reversed

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

 

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

  1. >>> a = iter('abcd')
  2. >>> next(a)
  3. 'a'
  4. >>> next(a)
  5. 'b'

 

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

 

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

  1. hasattr
  2. getattr
  3. setattr
  4. delattr
  5. callable
  6. isinstance
  7. issubclass
  8. __import__

 

11. 类型转换(24个)

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

    ord
  10. chr

  11. # 二进制八进制和十六进制
  12. bin 二进制
  13. hex 十六进制
  14. oct 八进制
  15. # 数据类型
  16. bool
  17. int
  18. float
  19. complax
  20. str
  21. tuple
  22. list
  23. dict
  24. set

 

bytearray

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

 

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

  1. >>> b = bytes(10)
  2. >>> b
  3. b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  4. >>> b[0]
  5. 0
  6. >>> b[1] = 1 #不可修改
  7. Traceback (most recent call last):
  8. File "<pyshell#6>", line 1, in <module>
  9. b[1] = 1
  10. TypeError: 'bytes' object does not support item assignment
  11. >>> b = bytearray(10)
  12. >>> b
  13. bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
  14. >>> b[1] = 1 #可修改
  15. >>> b
  16. bytearray(b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00')

 

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

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

 

frozenset

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

 

enumerate

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

 

slice 

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

 

super object(待定)

 

iter

  1. >>> a = iter([1,2,3]) # 创建一个可迭代对象
  2. >>> next(a)
  3. 1
  4. >>> next(a)
  5. 2
  6. >>> next(a)
  7. 3
  8. >>> next(a)
  9. Traceback (most recent call last):
  10. File "<stdin>", line 1, in <module>
  11. StopIteration
  12. >>>

 

range

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

 

ord , chr

  1. >>> ord('a') # unicode字符对应的整数
  2. 97
  3. >>> chr(97)   # 整数对应的unicode字符
  4. 'a'
  5. >>> ord('')
  6. 20013
  7. >>> ord('20013')
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. TypeError: ord() expected a character, but string of length 5 found
  11. >>> chr(20013)
  12. ''
  13. >>>

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号