九个在Python中调用函数的方法,任你选择
itomcoil 2024-12-07 08:59 26 浏览
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 类型注解的进阶应用:从静态检查到元编程
-
阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。如需转载请附上本文源链接!近年来,Python类型注解(TypeHinting)逐渐从一个可选的功能演变为大型...
- 高阶Python|返回类型提示技巧 (1)
-
引言Python提供了一种可选的特性——类型提示,它有助于提高代码的可读性、可推理性和可调试性。通过类型提示,开发者能够清楚地了解变量、函数参数和返回值应具备的数据类型。在开发那些需要高度灵活性的应用...
- 跟我一起学Python-函数的定义(基础)
-
一.函数的定义和调用1.语法:def函数名():函数封装的代码函数最好能够表达函数内部封装的代码功能,方便后续的调用,函数命名需要遵循规则字母、数字、下划线、不能以数字开头,不能使用系统关键字。...
- Python函数参数和返回值类型:让你的代码更清晰、更健壮
-
在Python开发中,你是否遇到过这些抓狂时刻?同事写的函数参数类型全靠猜调试两小时发现传了字符串给数值计算函数重构代码时不知道函数返回的是列表还是字典今天教你两招,彻底解决类型混乱问题!让你的...
- python入门到脱坑 函数—参数(python 参数处理)
-
本文包括必须参数,关键参数,默认参数以及可变参数Python函数参数详解一、位置参数(必需参数)位置参数是函数调用时必须提供的参数,且顺序必须与定义时一致。基本用法defgreet(name,me...
- python入门到脱坑经典案例—求两个数的和
-
下面为大家讲解如何求两个数之和——这是编程中最基础但最重要的算术运算之一。我们会从最简单的情况逐步深入,并穿插相关编程概念。1.最基础版本#定义两个变量num1=5num2=3#...
- 新手必看!30 个 Python 核心函数详解,手把手教你玩转编程
-
Python中30个核心函数及其含义、代码示例、注释和应用场景:print():用于输出文本或变量的值到控制台。message="Hello,World!"#定义一个...
- Python快速入门教程1:基本语法、数据类型、运算符、数字字符串
-
Python3的基础教程,涵盖了基本语法、数据类型、类型转换、解释器、注释、运算符、数字和字符串等内容,并附有使用实例场景。Python3的基础教程,涵盖了基本语法、数据类型、类型转换、解释器、注释、...
- 编程小白学做题:Python 的经典编程题及详解,附代码和注释(八)
-
适合Python3+的6道编程练习题(附详解)1找出字典中值最小的键题目描述:找出字典中值最小的键(如{"a":5,"b":2,"c...
- 新手学Python避坑,学习效率狂飙! 二十一、print()函数
-
感谢大家对《新手学Python避坑,学习效率狂飙!》系列的点赞、关注和收藏,今天这编是这个系列的第二十一个分享,前面还有二十个,大家可以关注下之前发布的文章。下面是我们今天第三个的分享:在Pytho...
- 编程小白学做题:Python 的经典编程题及详解,附代码和注释(六)
-
适合Python3+的6道编程练习题(附详解)1、打印杨辉三角的前n行题目描述:给定正整数n,打印杨辉三角的前n行(每个数等于它上方两数之和,每行首尾为1)。编写思路:杨辉三角的第i...
- 让你的Python代码更易读:7个提升函数可读性的实用技巧
-
如果你正在阅读这篇文章,很可能你已经用Python编程有一段时间了。今天,让我们聊聊可以提升你编程水平的一件事:编写易读的函数。请想一想:我们花在阅读代码上的时间大约是写代码的10倍。所以,每当你创建...
- python入门到脱坑 函数—return语句
-
Python函数中的return语句详解一、return语句基础1.1基本功能return语句用于从函数中返回一个值,并立即结束函数的执行。defadd(a,b):returna+...
- 编程小白学做题:Python 的经典编程题及详解,附代码和注释(七)
-
适合Python3+的6道编程练习题(附详解)1.检查字符串是否以指定子串开头题目描述:判断字符串是否以给定子串开头(如"helloworld"以"hello&...
- python的注释符是什么(python的合法注释符号是什么)
-
python的注释符是什么?python的注释符包括单行注释符和多行注释符。一、python单行注释符号(#)井号(#)常被用作单行注释符号,在代码中使用#时,它右边的任何数据都会被忽略,当做是注释。...
- 一周热门
- 最近发表
- 标签列表
-
- ps图案在哪里 (33)
- super().__init__ (33)
- python 获取日期 (34)
- 0xa (36)
- super().__init__()详解 (33)
- python安装包在哪里找 (33)
- linux查看python版本信息 (35)
- python怎么改成中文 (35)
- php文件怎么在浏览器运行 (33)
- eval在python中的意思 (33)
- python安装opencv库 (35)
- python div (34)
- sticky css (33)
- python中random.randint()函数 (34)
- python去掉字符串中的指定字符 (33)
- python入门经典100题 (34)
- anaconda安装路径 (34)
- yield和return的区别 (33)
- 1到10的阶乘之和是多少 (35)
- python安装sklearn库 (33)
- dom和bom区别 (33)
- js 替换指定位置的字符 (33)
- python判断元素是否存在 (33)
- sorted key (33)
- shutil.copy() (33)