如何在 Python 中调用函数?九种方法任你挑选
2023-03-20 15:02:03 时间
1.直接函数调用
这是最简单、最直观的方式:
def test():
print("This is a test")
test()
2.使用partial()函数
在 的内置库中functools
,有一个专用于生成偏函数的偏函数partial。
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
from functools import partial
power_2 = partial(power, n=2)
power_2(3) # output: 9
power_2(4) # output: 16
3. 使用 eval()
如果需要动态执行函数,可以使用 eval + string 来执行函数。
# demo.py
import sys
def pre_task():
print("running pre_task")
def task():
print("running task")
def post_task():
print("running post_task")
argvs = sys.argv[1:]
for action in argvs:
eval(action)()
执行:
$ python demo.py pre_task task post_task
running pre_task
running task
running post_task
4. 使用 getattr()
如果把所有的函数都放在类中,并定义为静态方法,就可以使用getattr()
get和调用它们。
import sys
class Task:
@staticmethod
def pre_task():
print("running pre_task")
@staticmethod
def task():
print("running task")
@staticmethod
def post_task():
print("running post_task")
argvs = sys.argv[1:]
task = Task()
for action in argvs:
func = getattr(task, action)
func()
5. 使用 __dict__()
我们都知道对象有一个__dict__()
魔法方法,它存储任何对象的属性和方法。
您可以调用类方法使用__dict__.get
import sys
class Task:
@staticmethod
def pre_task():
print("running pre_task")
func = Task.__dict__.get("pre_task")
func.__func__()
# Output
$ python /tmp/demo.py
running pre_task
6. 使用 global()
在 的内置库中functools
,有一个专用于生成偏函数的偏函数partial。
import sys
def pre_task():
print("running pre_task")
def task():
print("running task")
def post_task():
print("running post_task")
argvs = sys.argv[1:]
for action in argvs:
globals().get(action)()
# Output
$ python /tmp/demo.py pre_task task post_task
running pre_task
running task
running post_task
7. 从文本编译和运行
您可以在字符串中定义您的函数,并使用该compile
函数将其编译为字节码,然后用于exec
执行它。
pre_task = """
print("running pre_task")
"""
exec(compile(pre_task, '', 'exec'))
# Or from a text file
with open('source.txt') as f:
source = f.read()
exec(compile(source, 'source.txt', 'exec'))
8. 使用attrgetter()
在 的内置库中operator
,有一个获取属性的方法,称为attrgetter
,获取函数后执行。
from operator import attrgetter
class People:
def speak(self, dest):
print("Hello, %s" %dest)
p = People()
caller = attrgetter("speak")
caller(p)("Tony")
# Output
$ python /tmp/demo.py
Hello, Tony
9. 使用methodcaller()
还有一个methodcaller
方法在operator
from operator import methodcaller
class People:
def speak(self, dest):
print("Hello, %s" %dest)
caller = methodcaller("speak", "Tony")
p = People()
caller(p)
# Output
$ python /tmp/demo.py
Hello, Tony
相关文章
- Python中的函数与方法 以及Bound Method和Unbound Method
- 一文贯通python文件读取
- Python 中的异步编程:Asyncio
- 7个你现在就该学习Python的理由
- 提高Python运行效率的六个窍门
- Python数据科学:神经网络
- 一篇文章看懂大数据分析就业前景及职能定位
- R和Python中的文本挖掘:8个入门小贴士
- 告诉你为什么Python有点慢,但我却无所谓?
- 专注学习DevOps编程语言Top 5推荐
- Python发送邮件脚本
- Python多进程并行编程实践: mpi4py 的使用
- Python语言在未来的发展前景
- Python vs Ruby: 谁是最好的 web 开发语言?
- Python对Ruby:谁在Web开发领域更胜一筹?
- Python一行代码完成并行任务
- Python开发者2017应该关注的七个类库
- python爬虫入门基本知识
- 在终端中优雅地编写Python
- Python机器学习实战:信用卡欺诈检测