首页 > 解决方案 > 在 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")

标签: pythonpython-3.xfunctionloopsfor-loop

解决方案


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")

推荐阅读