zoukankan      html  css  js  c++  java
  • 014_内置函数

    1,内置函数

        截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数

      Built-in Functions  
    abs() dict() help() min() setattr()
    all() dir() hex() next() slice()
    any() divmod() id() object() sorted()
    ascii() enumerate() input() oct() staticmethod()
    bin() eval() int() open() str()
    bool() exec() isinstance() ord() sum()
    bytearray() filter() issubclass() pow() super()
    bytes() float() iter() print() tuple()
    callable() format() len() property() type()
    chr() frozenset() list() range() vars()
    classmethod() getattr() locals() repr() zip()
    compile() globals() map() reversed() __import__()
    complex() hasattr() max() round()  
    delattr() hash() memoryview() set()  

    2,作用域相关

      2.1,globals()——获取全局变量的字典

      2.2,locals()——获取所在域的变量的字典

    3,帮助

      3.1,dir()——查看其对象的所有方法

      3.2,callable()——看这个变量是不是可调用

        callable(参数),看这个变量是不是可调用。如果参数是一个函数名,就会返回True

    print(callable(print))
    

      3.3,help()——查看帮助信息     

        在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出,或者直接执行help(参数),查看和参数有关的操作

    help(str)
    

    4,模块相关

      4.1,__import__导入一个模块

    import time    #导入模块
    
    
    os = __import__('os')
    print(os.path.abspath('.'))
    

    5,文件操作相关 

      5.1,open()  

        open()  打开一个文件,返回一个文件操作符(文件句柄)

        操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)

        可以用encoding指定编码.

      5.2,判断文件是否可读,可写

    f = open('file')
    print(f.writable())
    print(f.readable())
    

    6,内存相关

      6.1,id(参数)—— 返回一个变量的内存地址

      6.2,hash(参数) ——返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

    • 可哈希(即不可更改的数据类型)
    • 每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变
    print(hash(123))
    print(hash('fskjs'))
    print(hash('fskjs'))
    print(hash([]))	#报错
    

      字典寻址方式(字典寻址快的原因):

              对键进行hash将得到的值作为地址,将键值存入该内存地址

    7,输入输出

      7.1,print()

    #def print(self, *args, sep=' ', end='
    ', file=None): # known special case of print
        """
        print(value, ..., sep=' ', end='
    ', file=sys.stdout, flush=False)
        file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
        sep:   打印多个值之间的分隔符,默认为空格
        end:   每一次打印的结尾,默认为换行符
        flush: 立即把内容输出到流文件,不作缓存
        """
    f = open('file','w')
    print('aaa',file=f)
    f.close
    #打印进度条
    import time
    for i in range(0,101,2): 
         time.sleep(0.1)
         char_num = i//2      #打印多少个'*' ,单'/'结果是float型,双'//'是整除,结果是int型
         per_str = '
    %s%% : %s
    ' % (i, '*' * char_num) if i == 100 else '
    %s%% : %s'%(i,'*'*char_num)
         print(per_str,end='', flush=True)   #'%%' 是打印'%'
    # 
     可以把光标移动到行首但不换行

      7.2,input()

    s = input("请输入内容 : ")  #输入的内容赋值给s变量
    print(s)  #输入什么打印什么。数据类型是str
    

    8,字符串类型代码的执行

      8.1,exec()和eval()都可以执行 字符串类型的代码;compile  将字符串类型的代码编译

    • exec和eval都可以执行 字符串类型的代码
    • eval不能常用,存在安全问题,因此只能用在你明确知道你要执行的代码是什么(即写死的代码)
    • eval有返回值——>有结果的简单计算
    • exec没有返回值——>简单的流程控制
    exec('print(123)')
    eval('print(123)')
    print(eval('1+2+3'))   
    print(exec('1+2+3'))
    

      

    code = '''for i in range(3):
    		print(i*'*')
    '''
    exec(code)
    

      8.2,compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

        将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。一次编译,可以一直使用

    参数说明:   

    1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  

    2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  

    3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

    #流程语句使用exec
    code1 = 'for i in range(0,10): print (i)'
    compile1 = compile(code1,'','exec')
    exec (compile1)
    
    #简单求值表达式用eval
    code2 = '1 + 2 + 3 + 4'
    compile2 = compile(code2,'','eval')
    eval(compile2)

     

    #交互语句用single
    >>>code3 = 'name = input("please input your name:")'
    >>>compile3 = compile(code3,'','single')
    >>>name   #执行前name变量不存在
    Traceback (most recent call last):
      File "<pyshell#29>", line 1, in <module>
        name
    NameError: name 'name' is not defined
    >>> exec(compile3)    #执行时显示交互命令,提示输入
    please input your name:pythoner
    >>> name 	#执行后name变量有值

    9,complex 复数

    数学中复数的虚部用 i 表示,在python中是用 j 表示
    浮点数:有限循环小数,无限循环小数
    小数:有限循环小数,无限循环小数,无限不循环小数

    10,进制转换

    print(bin(10))	# 0b1010 二进制
    print(oct(10))	# 0o12	 八进制
    print(hex(10))	# 0xa	 十六进制

    11,数学运算

      11.1,

    print(abs(-5))#求绝对值
    print(divmod(7,2)) #div除法 mod取余 #求商和余数
    print(round(3.14159,2))#精确值
    print(pow(2,3))#求幂运算
    print(pow(2,3,3))#幂运算之后再取余
    

      11.2,sum(iterable,start)

    #sum(iterable,start)
    #必须是可迭代的才能求和
    #start#从几开始加
    
    ret = sum([1,2,3,4,5],10)
    print(ret)
    

      11.3,min(iterable,key,defult)
         min(*args,key,defult)

    print(min(1,2,3,4))
    print(min([1,2,3,4]))
    print(min(1,2,3,-4,key = abs))#都换成绝对值后再求最小值

     

  • 相关阅读:
    Git
    Spring
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
  • 原文地址:https://www.cnblogs.com/eternity-twinkle/p/10512562.html
Copyright © 2011-2022 走看看