python - 在 For 循环 Python 中更改函数名称
问题描述
我想通过使用 for 循环,通过在 for 循环中更改函数名称来运行所有这些函数
# 1
def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
# 2
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
for i in range (2):
func_statement = (any_lowercase+i) #I tried converting this to a string it didn't work ("any_lowercase"+str(i+1))
print("Word 'Hello' islowercase-" , func_statement("Hello"))
print("Word 'hello' islowercase-", func_statement("hello"))
print("Word 'HELLO' islowercase-", func_statement("HELLO"))
print("Word 'heLlO' islowercase-", func_statement("heLlO"))
print("\n")
解决方案
Python 的函数是一流的对象(感谢@ShadowRanger),这意味着您可以将函数作为参数传递给其他函数,将对它们的引用存储在集合中,等等。
def f1():
pass
def f2():
pass
def f3():
pass
list_of_functions = [f1, f2, f3]
for func in list_of_functions:
func()
引用函数的方法是不调用函数(即使用括号)。因此,如果您有一个函数any_lowercase1
,那么要以列表之类的顺序存储对该函数的引用,例如,您只需存储函数的名称:
list_of_lowercase_funcs = [any_lowercase1, any_lowercase2]
for func in list_of_lowercase_funcs:
print("Word 'Hello' islowercase-", func("Hello"))
print("Word 'hello' islowercase-", func("hello"))
print("Word 'HELLO' islowercase-", func("HELLO"))
print("Word 'heLlO' islowercase-", func("heLlO"))
print("\n")
推荐阅读
- fortran - 编写一个接受任何两个数字(任何实数或任何整数)的函数
- git - 如何在 git 分支中获取给定作者的提交消息历史记录?
- bots - 聊天机器人的默认消息
- bash - 查找文件的一行,提取其中的一部分并在 Bash 中的同一位置替换
- node.js - Sequelize COUNT 在 INCLUDE 关联返回错误聚合函数或 GROUP BY 子句
- vb.net - 如何将主要重复错误更改为窗口形式的消息框
- javascript - Selenium:捕获 DOM 元素图像
- docker - 使用另一个镜像运行测试用例的 Docker 镜像
- c - 连接客户端/服务器以进行 UDP 广播的正确方法
- r - R删除所有以字符串开头的列都有NA的行