[Python]执行环境--可执行内建函数

参考:《Python核心编程》 14章前半部分

内建函数相关知识:

内建函数:BIFs

属性: 
bif.__doc__
bif.__name__
bif.__self__
bif.__module__

用户函数:UDF

属性:
udf.__doc__  文档字符串
udf.__name__  函数名称
udf.func_code  字节编译的代码对象
udf.func_globals 全局名字空间字典
udf.func_dict 函数属性的名字空间
udf.func_doc 
udf.func_name
udf.func_closure


从类的角度

内建方法:BIMs (只有对应的BIT才有对应的BIM)

用户方法:UDM



类的实例化就是“调用”类
方法绑定和非绑定: 就是有没有实例去调用方法
类中方法:
__init__ 相当于构造函数


可执行对象函数:

callable(obj) 判断obj是否可以调用,也就是对象是否可以用()来调用
def fun():
    pass
    
callable(fun)
True
func = fun()
callable(func)
False


compile() 允许程序员在运行时刻迅速生成代码对象,然后使用exec或者eval()执行这些对象
In [16]: help(compile)
Help on built-in function compile in module __builtin__:


compile(...)
    compile(source, filename, mode[, flags[, dont_inherit]]) -> code object


    Compile the source string (a Python module, statement or expression)
    into a code object that can be executed by the exec statement or eval().
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if non-zero, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or zero these statements do influence the compilation,
    in addition to any features explicitly specified.


从文档中出第三个参数是mode,一般有三个选择
'eval'  可求值的表达式
'single' 单一可执行的语句
'exec' 可执行的语句组
ex:
In [17]: eval_code = compile('3+3','','eval')


In [18]: eval(eval_code)
Out[18]: 6


In [20]: single_code = compile('print "hello world"','','single')


In [21]: exec single_code
hello world


In [24]: exec_code = compile("""
   ....: print 'some num'
   ....: for i in range(5):
   ....:         print i
   ....:     """,'','exec')


In [25]: exec exec_code
some num
0
1
2
3
4

eval() :对表达式求值
In [26]: eval('100+100.0')
Out[26]: 200.0


exec() :接受一个参数,执行代码对象或者是字符串代码,也可以获取打开程序文件执行,每次执行到达文件的末尾
In [28]: exec """
   ....: print range(5)
   ....: """
[0, 1, 2, 3, 4]

input() :是eval 和raw_input的组合,eval(raw_input())
In [30]: input('please a expression ')
please a expression 3+3
Out[30]: 6




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值