简介
利用Python编写函数时,可以直接定义,也可以在 class 中作为方法定义。那么执行函数的方法你真的全知道吗?
方法一
直接调用,例如:
1 2 3 4 |
def finthon(): print('This is Finthon!') finthon() # Output: This is Finthon! |
在类中,也是直接调用该方法:
1 2 3 4 5 6 |
Class Finthon: def finthon(self): print('This is Finthon!') f = Finthon() f.finthon() # Output: This is Finthon! |
方法二
利用 functools 库中的 partial 方法生成偏函数:
1 2 3 4 5 6 7 8 |
from functools import partial def finthon(x): print(x**2) f = partial(finthon) f(2) # Output: 4 f(3) # Output: 9 |
方法三
eval() 方法+字符串执行函数:
1 2 3 4 5 6 |
def finthon(): print('This is Finthon!') astring = 'finthon' eval(astring)() # Output: This is Finthon! # 等价于 finthon() |
方法四
从文本中编译运行:
1 2 3 4 5 6 |
finthon = """ a = 1 + 2 print(a) """ exec(compile(finthon, '<string>', 'exec')) # Output: 3 |
当然也可以直接从文本文件中运行:
1 2 3 |
with open('finthon.txt') as f: con = f.read() exec(compile(con, 'finthon.txt', 'exec')) |
总结
以上就是可以执行函数的方法,尤其是通过文本执行,在有些场合可以巧妙用上。