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

2.3.9 python 内置函数

程序员文章站 2023-11-27 15:44:34
解释器启动时就定义好的方法 https://docs.python.org/3/library/functions.html?highlight=built#ascii 1.eval函数 函数的作用: 计算指定表达式的值。也就是说它要执行的python代码只能是单个表达式(注意eval不支持任何形式 ......

解释器启动时就定义好的方法

 https://docs.python.org/3/library/functions.html?highlight=built#ascii

 

 Built-In Functions    
 

 

1.eval函数

函数的作用:

计算指定表达式的值。也就是说它要执行的python代码只能是单个表达式(注意eval不支持任何形式的赋值操作),而不能是复杂的代码逻辑。

eval(source, globals=None, locals=None, /)

参数说明:

source:必选参数,可以是字符串,也可以是一个任意的code(代码)对象实例(可以通过complie函数创建)。如果它是一个字符串,它会被当作一个(使用globals和locals参数作为全局和本地命名空间的)python表达式进行分析和解释。

globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。

locals:可选参数,表示全局命名空间(存放局部变量),如果被提供,可以是任何映射对象。如果参数被忽略,那么它将会取与globals相同的值。

如果globals与locals都被忽略,那么它们将取eval()函数被调用环境下的全局命名空间和局部命名空间。

返回值:

如果source是一个code对象,且创建该code对象时,complie函数的mode参数是‘exec’,那么eval()函数的返回值是None;

否则,如果source是一个输出语句,如print(),则eval()返回结果为None;

否则,source表达式的结果就是eval()函数的返回值

实例:

2.3.9 python 内置函数
x = 10
def func():
    y = 20   #局部变量y
    a = eval("x+y")
    print("a:",a)      #x没有就调用全局变量
    b = eval("x+y",{"x":1,"y":2})     #定义局部变量,优先调用
    print("b:",b)
    c = eval("x+y",{"x":1,"y":2},{"y":3,"z":4})  
    print("c:",c)  
    d = eval("print(x,y)")
    print("d:",d)   #对于变量d,因为print()函数不是一个计算表达式,因此没有返回值
func()
2.3.9 python 内置函数

输出结果:

a: 30
b: 3
c: 4
10 20
d: None

 

2.exec函数

函数的作用:

动态执行python代码。也就是说exec可以执行复杂的python代码,而不像eval函数那样只能计算一个表达式的值。

exec(source, globals=None, locals=None, /)

source:必选参数,表示需要被指定的python代码。它必须是字符串或code对象。如果source是一个字符串,该字符串会先被解析为一组python语句,然后执行。如果source是一个code对象,那么它只是被简单的执行。

返回值:

exec函数的返回值永远为None。

 

eval()函数和exec()函数的区别:

eval()函数只能计算单个表达式的值,而exec()函数可以动态运行代码段。

eval()函数可以有返回值,而exec()函数返回值永远为None。

例1:

我们把eval中的例子拿过来执行

2.3.9 python 内置函数
x = 10
def func():
    y = 20
    a = exec("x+y")
    print("a:",a)
    b = exec("x+y",{"x":1,"y":2})
    print("b:",b)
    c = exec("x+y",{"x":1,"y":2},{"y":3,"z":4})
    print("c:",c)
    d = exec("print(x,y)")
    print("d:",d)
func()
2.3.9 python 内置函数

执行结果:

2.3.9 python 内置函数
#exec不会有任何返回值
a: None   
b: None
c: None
10 20
d: None
2.3.9 python 内置函数

例2

2.3.9 python 内置函数
x = 10
expr = """
z = 30
sum = x + y + z   #一大包代码
print(sum)
"""
def func():
    y = 20
    exec(expr)   10+20+30
    exec(expr,{'x':1,'y':2}) 30+1+2
    exec(expr,{'x':1,'y':2},{'y':3,'z':4}) #30+1+3,x是定义全局变量1,y是局部变量

func()
2.3.9 python 内置函数

执行结果:

60
33
34

 

3.complie函数

函数的作用:

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

参数说明

source:字符串或AST对象,表示需要进行编译的python代码

filename:指定需要编译的代码文件,如果不是文件读取代码则传递一些可辨认的值。

mode:用于标识必须当做那类代表来编译;如果source是由一个代码语句序列组成,则指定mode=‘exec’,如果source由单个表达式组成,则指定mode=‘eval’;如果source是由一个单独的交互式语句组成,则指定modo=‘single’。必须要制定,不然肯定会报错。

例子:

2.3.9 python 内置函数
s = """              #一大段代码
for x in range(10):
    print(x, end='')  
print()
"""
code_exec = compile(s, '<string>', 'exec')   #必须要指定mode,指定错了和不指定就会报错。
code_eval = compile('10 + 20', '<string>', 'eval')   #单个表达式
code_single = compile('name = input("Input Your Name: ")', '<string>', 'single')   #交互式

a = exec(code_exec)   使用的exec,因此没有返回值
b = eval(code_eval)  

c = exec(code_single)  交互
d = eval(code_single)

print('a: ', a)
print('b: ', b)
print('c: ', c)
print('name: ', name)
print('d: ', d)
print('name; ', name)
2.3.9 python 内置函数

执行结果:

1 0123456789  #有print就会打印
2 Input Your Name: kebi
3 Input Your Name: kebi
4 a:  None
5 b:  30
6 c:  None
7 name:  kebi
8 d:  None
9 name;  kebi

 


 

map , filter , reduce

 1 >>> import functools
 2 >>> help(functools.reduce)
 3 Help on built-in function reduce in module _functools:
 4 
 5 reduce(...)
 6     reduce(function, sequence[, initial]) -> value
 7     
 8     Apply a function of two arguments cumulatively to the items of a sequence,
 9     from left to right, so as to reduce the sequence to a single value.
10     For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
11     ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
12     of the sequence in the calculation, and serves as a default when the
13     sequence is empty.
14 
15 >>> help(map)
16 Help on class map in module builtins:
17 
18 class map(object)
19  |  map(func, *iterables) --> map object
20  |  
21  |  Make an iterator that computes the function using arguments from
22  |  each of the iterables.  Stops when the shortest iterable is exhausted.
23  |  
24  |  Methods defined here:
25  |  
26  |  __getattribute__(self, name, /)
27  |      Return getattr(self, name).
28  |  
29  |  __iter__(self, /)
30  |      Implement iter(self).
31  |  
32  |  __new__(*args, **kwargs) from builtins.type
33  |      Create and return a new object.  See help(type) for accurate signature.
34  |  
35  |  __next__(self, /)
36  |      Implement next(self).
37  |  
38  |  __reduce__(...)
39  |      Return state information for pickling.
40 
41 >>> help(filter)
42 Help on class filter in module builtins:
43 
44 class filter(object)
45  |  filter(function or None, iterable) --> filter object
46  |  
47  |  Return an iterator yielding those items of iterable for which function(item)
48  |  is true. If function is None, return the items that are true.
49  |  
50  |  Methods defined here:
51  |  
52  |  __getattribute__(self, name, /)
53  |      Return getattr(self, name).
54  |  
55  |  __iter__(self, /)
56  |      Implement iter(self).
57  |  
58  |  __new__(*args, **kwargs) from builtins.type
59  |      Create and return a new object.  See help(type) for accurate signature.
60  |  
61  |  __next__(self, /)
62  |      Implement next(self).
63  |  
64  |  __reduce__(...)
65  |      Return state information for pickling.
66 
67 >>>