欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python学习日记(十一) 内置函数

程序员文章站 2022-07-01 23:03:24
什么是内置函数? 就是Python中已经写好了的函数,可以直接使用 内置函数图表: 以3.6.2为例 内置函数分类: 一、反射相关 二、基础数据类型相关 1.和数字相关 (1)数据类型 a.bool() 把一个值转换成布尔值 b.int() 把一个值转换成整型 c.float() 把一个整数或数字字 ......

什么是内置函数?

就是python中已经写好了的函数,可以直接使用

 

内置函数图表:

以3.6.2为例

Python学习日记(十一) 内置函数

 

内置函数分类:

一、反射相关

二、基础数据类型相关

1.和数字相关

(1)数据类型

  a.bool()

    把一个值转换成布尔值

li = ['',[],1,12,0]
for i in li:
    print(bool(i))
# false
# false
# true
# true
# false

  b.int()

    把一个值转换成整型

num = input('please input a number:')
print(10 + int(num))
# please input a number:20
# 30

  c.float()

    把一个整数或数字字符串转换成带小数点的数

print(float('123.5'),type(float('123.5')))      #123.5 <class 'float'>
print(float(-50.2),type(float(-50.2)))          #-50.2 <class 'float'>

  d.complex()

    返回一个复数

a = 1 + 2j
b = 2
print(complex(a))   #(1+2j)
print(complex(b))   #(2+0j)
print(complex(2,3)) #(2+3j)

(2)进制转换

  a.bin()

    将一个数以二进制字符串的方式表示

print(bin(2))   #0b10
print(bin(10))  #0b1010

  b.oct()

    把一个数转换成八进制的字符串

print(oct(20),type(oct(20)))    #0o24 <class 'str'>
print(oct(8),type(oct(8)))      #0o10 <class 'str'>

  c.hex()

    把一个数字转换成十六进制的字符串

print(hex(10),type(hex(10)))    #0xa <class 'str'>
print(hex(28),type(hex(28)))    #0x1c <class 'str'>

(3)数学运算

  a.abs()

    对一个数的值取绝对值,结果不改变原值

a = -5
print(abs(a))   #5

  b.divmod()

    返回一个以商和余数组成的元祖

print(divmod(10,5),type(divmod(10,5)))      #(2, 0) <class 'tuple'>
print(divmod(4,9))                          #(0, 4)

  c.round()

    将浮点值四舍五入

import math
pi = math.pi
print(round(pi,4))      #3.1416

  d.pow()

    一般情况下给函数两个数可以计算次方,若给定三个数则在幂运算后再取余

print(pow(2,3))     #8
print(pow(2,0.5))   #1.4142135623730951
print(pow(3,2,2))   #1

  e.sum()

print(sum([2,2,3,5,6,2,4]))        #24
print(sum([2,2,3,5,6,2,4],10))     #34  这里只是先让10进行sum的运算

  f.min()

print(min(-1,-2,2,3))                    #-2
print(min(-1,-2,2,3,key=abs))            #-1
print(min('aab','aaab','bc',key=len))    #bc

  g.max()

print(max(-4,-2,2,3))                    #3
print(max(-4,-2,2,3,key=abs))            #-4
print(max('aab','aaab','bc',key=len))    #aaab

2.和数据结构相关

(1)

三、作用域相关

1.locals()

  找到当前作用域下所有的变量对应关系,并以字典返回

2.globals()

  找到全局作用域下所有的变量对应关系,并以字典返回

a = 1
b = 'hello'
def func():
    c = 3
    print(locals())     #{'c': 3}
    print(globals())    #{'__name__': '__main__', '__loader__': <_frozen_importlib_external.sourcefileloader object at 0x002a5910>,
                        # 'func': <function func at 0x00527cd8>, '__file__': 'c:/users/administrator/pycharmprojects/pyl/生成器/1.py',
                        # '__spec__': none, '__cached__': none, 'a': 1, '__builtins__': <module 'builtins' (built-in)>, 'b': 'hello',
                        # '__doc__': none, '__package__': none}
func()

四、面向对象相关

五、迭代器/生成器相关

1.range()

用于创建一个整数列表,常用在for循环中

li = list(range(0,11,2))
print(li)   #[0, 2, 4, 6, 8, 10]

2.__next__()

一个next对应一个值返回,如果这个迭代器已经没有值可以返回了那么就将报错

li = ['a',1,2]
iterator = li.__iter__()
print(iterator.__next__())      #a
print(iterator.__next__())      #1

3.__iter__()

当一个具有可迭代数据使用__iter__()它会返回一个迭代器的内存地址

li = ['a',1,2]
iterator = li.__iter__()
print(iterator)         #<list_iterator object at 0x0000000002202f60>

六、其他

1.输入输出

(1)input()

content = input('请输入一个数:')
print(content)
# 请输入一个数:5
# 5

(2)print()

特殊字符分隔

print('a','b','c',sep = '&&',end = '')  #a&&b&&c

将用户输入的数据直接写入文件

f = open('file',mode='w',encoding='utf-8')
content = input()
print(content,sep=',',end='',file = f,flush=true)  #file默认是输出到屏幕,如果设置文件句柄则输出到文件
                                                   #flush立即将内容输出到文件流,不留缓存
f.close()

2.内存相关

(1)hsah()

这里hash()中用到的参数必须是不可变数据类型,hash()完后结果会返回一串数字

print(hash(133))        #133
print(hash('aaaaa'))    #-868214941
print(hash('aaaax'))    #519685031
print(hash((1,2,3)))    #-378539185

最直接的例子就是字典键的值,字典中的key是唯一的并且只能对应一个hash值

(2)id()

返回一个变量的内存地址

a = 5
b = 'hello'
c = [1,2]
print(id(a))    #490310160
print(id(b))    #4872512
print(id(c))    #6656288

3.字符串类型代码的执行

(1)eval()

可以执行字符串类型的代码,有返回值,适用于简单计算

建议一般情况下不要使用eval()除非自己很明确要执行什么

print(eval('123'))              #123
print(eval('1 + 2 + 3 + 4'))    #10

(2)exec()

可以执行字符串类型的代码,无返回值,适用于简单流程控制

print(exec('123'))                  #none
print(exec('1 + 2 + 3 + 4 + 5'))    #none
code = '''for i in [1,5,10]:
                print(i*2)'''
exec(code)
# 2
# 10
# 20

(3)complie()

compile(source, filename, mode, flags=0, dont_inherit=false, optimize=-1)
source:字符串或者ast
filename:代码文件的名称,如果不是从文件中读取代码则传递一些可辨认的值。当传入source参数时,filename参数传空即可
model:编译代码的种类 eval属于计算类、exec属于流程类、single属于交互类

计算类:

code = '2*5/10 + 6'
ret = compile(code,'','eval')
print(eval(ret))    #7.0

流程类:

code = '''print([i*i for i in range(10) if i > 5])'''
ret = compile(code,'','exec')
exec(ret)   #[36, 49, 64, 81]

交互类:

code = "name = input('please input your name:')"
ret = compile(code,'','single')
exec(ret)
print(name)

4.文件操作相关

(1)open()

打开一个文件的相关操作

5.模块相关

(1)__import__()

# import time
time = __import__('time')
print(time.time())

6.帮助

(1)help()

能够查看一个变量或类型的方法

help(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.
#  |  
#  |  method resolution order:
#  |      bool
#  |      int
#  |      object
#  |  
#  |  methods defined here:
#  |  
#  |  __and__(self, value, /)
#  |      return self&value.
#  |  
#  |  __new__(*args, **kwargs) from builtins.type
#  |      create and return a new object.  see help(type) for accurate signature.
#  |  
#  |  __or__(self, value, /)
#  |      return self|value.
#  |  
#  |  __rand__(self, value, /)
#  |      return value&self.
#  |  
#  |  __repr__(self, /)
#  |      return repr(self).
#  |  
#  |  __ror__(self, value, /)
#  |      return value|self.
#  |  
#  |  __rxor__(self, value, /)
#  |      return value^self.
#  |  
#  |  __str__(self, /)
#  |      return str(self).
#  |  
#  |  __xor__(self, value, /)
#  |      return self^value.
#  |  
#  |  ----------------------------------------------------------------------
#  |  methods inherited from int:
#  |  
#  |  __abs__(self, /)
#  |      abs(self)
#  |  
#  |  __add__(self, value, /)
#  |      return self+value.
#  |  
#  |  __bool__(self, /)
#  |      self != 0
#  |  
#  |  __ceil__(...)
#  |      ceiling of an integral returns itself.
#  |  
#  |  __divmod__(self, value, /)
#  |      return divmod(self, value).
#  |  
#  |  __eq__(self, value, /)
#  |      return self==value.
#  |  
#  |  __float__(self, /)
#  |      float(self)
#  |  
#  |  __floor__(...)
#  |      flooring an integral returns itself.
#  |  
#  |  __floordiv__(self, value, /)
#  |      return self//value.
#  |  
#  |  __format__(...)
#  |      default object formatter
#  |  
#  |  __ge__(self, value, /)
#  |      return self>=value.
#  |  
#  |  __getattribute__(self, name, /)
#  |      return getattr(self, name).
#  |  
#  |  __getnewargs__(...)
#  |  
#  |  __gt__(self, value, /)
#  |      return self>value.
#  |  
#  |  __hash__(self, /)
#  |      return hash(self).
#  |  
#  |  __index__(self, /)
#  |      return self converted to an integer, if self is suitable for use as an index into a list.
#  |  
#  |  __int__(self, /)
#  |      int(self)
#  |  
#  |  __invert__(self, /)
#  |      ~self
#  |  
#  |  __le__(self, value, /)
#  |      return self<=value.
#  |  
#  |  __lshift__(self, value, /)
#  |      return self<<value.
#  |  
#  |  __lt__(self, value, /)
#  |      return self<value.
#  |  
#  |  __mod__(self, value, /)
#  |      return self%value.
#  |  
#  |  __mul__(self, value, /)
#  |      return self*value.
#  |  
#  |  __ne__(self, value, /)
#  |      return self!=value.
#  |  
#  |  __neg__(self, /)
#  |      -self
#  |  
#  |  __pos__(self, /)
#  |      +self
#  |  
#  |  __pow__(self, value, mod=none, /)
#  |      return pow(self, value, mod).
#  |  
#  |  __radd__(self, value, /)
#  |      return value+self.
#  |  
#  |  __rdivmod__(self, value, /)
#  |      return divmod(value, self).
#  |  
#  |  __rfloordiv__(self, value, /)
#  |      return value//self.
#  |  
#  |  __rlshift__(self, value, /)
#  |      return value<<self.
#  |  
#  |  __rmod__(self, value, /)
#  |      return value%self.
#  |  
#  |  __rmul__(self, value, /)
#  |      return value*self.
#  |  
#  |  __round__(...)
#  |      rounding an integral returns itself.
#  |      rounding with an ndigits argument also returns an integer.
#  |  
#  |  __rpow__(self, value, mod=none, /)
#  |      return pow(value, self, mod).
#  |  
#  |  __rrshift__(self, value, /)
#  |      return value>>self.
#  |  
#  |  __rshift__(self, value, /)
#  |      return self>>value.
#  |  
#  |  __rsub__(self, value, /)
#  |      return value-self.
#  |  
#  |  __rtruediv__(self, value, /)
#  |      return value/self.
#  |  
#  |  __sizeof__(...)
#  |      returns size in memory, in bytes
#  |  
#  |  __sub__(self, value, /)
#  |      return self-value.
#  |  
#  |  __truediv__(self, value, /)
#  |      return self/value.
#  |  
#  |  __trunc__(...)
#  |      truncating an integral returns itself.
#  |  
#  |  bit_length(...)
#  |      int.bit_length() -> int
#  |      
#  |      number of bits necessary to represent self in binary.
#  |      >>> bin(37)
#  |      '0b100101'
#  |      >>> (37).bit_length()
#  |      6
#  |  
#  |  conjugate(...)
#  |      returns self, the complex conjugate of any int.
#  |  
#  |  from_bytes(...) from builtins.type
#  |      int.from_bytes(bytes, byteorder, *, signed=false) -> int
#  |      
#  |      return the integer represented by the given array of bytes.
#  |      
#  |      the bytes argument must be a bytes-like object (e.g. bytes or bytearray).
#  |      
#  |      the byteorder argument determines the byte order used to represent the
#  |      integer.  if byteorder is 'big', the most significant byte is at the
#  |      beginning of the byte array.  if byteorder is 'little', the most
#  |      significant byte is at the end of the byte array.  to request the native
#  |      byte order of the host system, use `sys.byteorder' as the byte order value.
#  |      
#  |      the signed keyword-only argument indicates whether two's complement is
#  |      used to represent the integer.
#  |  
#  |  to_bytes(...)
#  |      int.to_bytes(length, byteorder, *, signed=false) -> bytes
#  |      
#  |      return an array of bytes representing an integer.
#  |      
#  |      the integer is represented using length bytes.  an overflowerror is
#  |      raised if the integer is not representable with the given number of
#  |      bytes.
#  |      
#  |      the byteorder argument determines the byte order used to represent the
#  |      integer.  if byteorder is 'big', the most significant byte is at the
#  |      beginning of the byte array.  if byteorder is 'little', the most
#  |      significant byte is at the end of the byte array.  to request the native
#  |      byte order of the host system, use `sys.byteorder' as the byte order value.
#  |      
#  |      the signed keyword-only argument determines whether two's complement is
#  |      used to represent the integer.  if signed is false and a negative integer
#  |      is given, an overflowerror is raised.
#  |  
#  |  ----------------------------------------------------------------------
#  |  data descriptors inherited from int:
#  |  
#  |  denominator
#  |      the denominator of a rational number in lowest terms
#  |  
#  |  imag
#  |      the imaginary part of a complex number
#  |  
#  |  numerator
#  |      the numerator of a rational number in lowest terms
#  |  
#  |  real
#  |      the real part of a complex number

7.调用相关

(1)callable()

判断参数是否是一个可调用的函数名,若是则true,不是则false

a = 1
print(callable(a))  #false
def func():
    return 5
print(callable(func))     #true
print(callable(func()))   #false

8.查看内置属性

(1)dir()

查看一个参数或变量的属性

print(dir([]))  #['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']