zoukankan      html  css  js  c++  java
  • python 核心编程 第十四章

    python 运行外部程序或内部动态生成的程序段

    函数

    1. 内建函数(BIFs)
      BIF 属性 描述
      bif.doc 文档字符串(或 None)
      bif.name 字符串类型的文档名字
      bif.self 设置为 None(保留给 built-in 方法)
      bif.module 存放 bif 定义的模块名字(或 None)
    2. 用户定义的函数属性(UDF)
      UDF 属性 描述
      udf.doc 文档字符串(也可以用 udf.func_doc)
      udf.name 字符串类型的函数名字(也可以用 udf.func_name)
      udf.func_code 字节编译的代码对象
      udf.func_defaults 默认的参数元组
      udf.func_globals 全局名字空间字典; 和从函数内部调用 globals(x)一样
      udf.func_dict 函数属性的名字空间
      udf.func_doc (见上面的 udf.doc)
      udf.func_name (见上面的 udf.name)
      udf.func_closure 包含了自由变量的引用的单元对象元组(自用变量在 UDF 中使用,但在别处定义;参见 python[语言]参考手册)

    方法

    1. 内建方法(BIM)属性
      BIM 属性 描述
      bim.doc 文档字串
      bim.name 字符串类型的函数名字
      bim.self 绑定的对象
    2. 用户自定义的方法(UDM)
      UDM 属性 描述
      udm.doc 文档字符串(与 udm.im_fuc.__doc__相同)
      udm.name 字符串类型的方法名字(与 umd.im_func.__name__相同)
      udm.module 定义 udm 的模块的名字(或 none)
      udm.im_class 方法相关联的类 (对于绑定的方法; 如果是非绑定, 那么为要求 udm 的类)
      udm.im_func 方法的函数对象(见 UDFs)
      udm.im_self 如果绑定的话为相关联的实例,如果非绑定位为 none

    调用类的实例,需要实现__call__方法

    代码对象

    1. callable():
      确定一个函数是否是可调用对象,也就是是否可以通过函数操作"()"来调用,返回一个布尔值。
    2. compile():代码运行时,生成代码对象。
      compile 的三个参数都是必需的,第一参数代表了要编译的 python 代码。第二个字符串,虽然
      是必需的,但通常被置为空串。该参数代表了存放代码对象的文件的名字(字符串类型) 。compile 的
      通常用法是动态生成字符串形式的 Python 代码, 然后生成一个代码对象——代码显然没有存放在
      任何文件。
      最后的参数是个字符串,它用来表明代码对象的类型。有三个可能值:
      'eval' 可求值的表达式[和 eval()一起使用]
      'single' 单一可执行语句[和 exec 一起使用]
      'exec' 可执行语句组[和 exec 一起使用]
    eval_code = compile("100+2", "", "eval")
    single_code = compile(r"print 'Hello world!'", "", 'single')
    exec_code = compile("""
    req = input("Count how many numbers?")
    for eachNum in range(req):
        print eachNum
    """, "", "exec")
    eval(eval_code)
    exec single_code
    exec exec_code
    
    
    Hello world!
    Count how many numbers?3
    0
    1
    2
    
    1. exec 可以直接使用字符串执行,但如果使用compil()速度会更快一点。 他还可以接受python文件对象
    f = open("text.txt")
    exec f
    f.seek(0)
    exec f
    

    之所以使用seek()的原因是,调用一次exec后文件指针会在文件最末尾,这样在调用一次exec就如同没有效用一样
    4. input() 等价于 eval(raw_input())

    在python运行时生成和执行python代码

    dashes = "
    " + "- " * 50
    exec_dict = {"f":"""
    for %s in %s:
        print %s""", "s": """
    %s = 0
    %s = %s
    while %s < len(%s):
        print %s[%s]
        %s = %s +1""", "n": """
    %s = %d
    while %s < %d:
    print %s
    %s = %s + %d"""}
    
    def main():
        ltype = raw_input("loop type?(For/While)")
        dtype = raw_input("Data type?(Number/Seq)")
        if dtype == "n":
            start = input("Starting value")
            stop = input("Ending value (Non-inclusive)?")
            step = input("stepping value?")
            seq = str(range(start, stop, step))
        else:
            seq = raw_input("enter sequence?")
        var = raw_input("Iterative variable name?")
        if ltype == "f":
            exec_str = exec_dict["f"] % (var, seq, var)
        elif ltype == 'w':
            if dtype == "s":
                svar = raw_input("enter sequence name?")
                exec_str = exec_dict["s"]%(var, svar, seq, var, svar, svar, var, var, var)
            elif dtype == "n":
                exec_str = exec_dict["n"]%(var, start, var, stop, var, var, var, step)
        print dashes
        print exec_str, dashes
        exec exec_str
        print dashes
    
    if __name__ == '__main__':
        main()
    

    有条件的执行代码

    def bar():
        return True
    def foo():
        "foo() does not do much"
        return True
    
    bar.__doc__ = "bar() does not do much"
    foo.tester = """
    if foo():
        print 'PASSED'
    else:
        print 'FAILED'"""
    print dir()
    for eachAttr in dir():
        obj = eval(eachAttr)
        if isinstance(obj, type(foo)):
            if hasattr(obj, "__doc__"):
                print "
    function '%s' has a doc string:
    	%s" % (eachAttr, obj.__doc__)
            if hasattr(obj, "tester"):
                print "function '%s' has a tester...executing" % eachAttr
                exec obj.tester
            else:
                print "function '%s' has no tester...skipping" % eachAttr
        else:
            print "%s is not a function" % eachAttr
    

    程序输出

    ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'bar', 'foo']
    __builtins__ is not a function
    __doc__ is not a function
    __file__ is not a function
    __name__ is not a function
    __package__ is not a function
    
    function 'bar' has a doc string:
       bar() does not do much
    function 'bar' has no tester...skipping
    
    function 'foo' has a doc string:
       foo() does not do much
    function 'foo' has a tester...executing
    PASSED
    

    执行其他python程序

    execfile()函数
    execfile(filename, globals=globals(), locals=locals())

    执行其他非python程序

    os.system()执行命令行
    os.popen()

    此章练习跳过

  • 相关阅读:
    linux下安装tomcat
    linux 中安装mysql8.0
    国家助学贷款
    语句摘录
    Java 今天是否为节假日
    Jfinal框架登陆页面的图形验证码
    ActiveRecord初始化,可以实现jfinal系统启动完成后,再建立数据库连接
    socket 通讯
    datatable的excel导入,其中有关于datatables的很多参数设置
    jfinal form表单提交文件
  • 原文地址:https://www.cnblogs.com/jikeboy/p/6028590.html
Copyright © 2011-2022 走看看