Python 如何遍历另一个文件中的函数名并调用该函数
由于我对python还不熟悉,所以我一直在努力解决这个问题。我有A.py和B.py文件。我目前正在尝试在a.py中编写一个函数,该函数将迭代B.py中的所有函数名,并在满足条件时调用该函数。我还导入了这些文件。有什么想法吗Python 如何遍历另一个文件中的函数名并调用该函数,python,python-3.x,Python,Python 3.x,由于我对python还不熟悉,所以我一直在努力解决这个问题。我有A.py和B.py文件。我目前正在尝试在a.py中编写一个函数,该函数将迭代B.py中的所有函数名,并在满足条件时调用该函数。我还导入了这些文件。有什么想法吗 Pseudo code for A.py For function name in B.py If functionname == functionOne Call that function() Example for B.py def funct
Pseudo code for A.py
For function name in B.py
If functionname == functionOne
Call that function()
Example for B.py
def functionOne():
Print("this is one")
def functionTwo():
Print("this is two")
结果=getattr(b,'functionOne')()
结果()
查看:result=getattr(b,'functionOne')()
结果()
查看:一种方法是使用
dir()
内置函数,该函数返回指定对象的所有属性和方法,不带值。您可以迭代dir()
并过滤需要调用的函数名。要调用该函数,我们可以使用getattr()
函数,该函数从指定对象返回指定属性的值
使用:
输出:
>>> python A.py
this is one
this is two
一种方法是使用内置函数
dir()
,该函数返回指定对象的所有属性和方法,但不返回值。您可以迭代dir()
并过滤需要调用的函数名。要调用该函数,我们可以使用getattr()
函数,该函数从指定对象返回指定属性的值
使用:
输出:
>>> python A.py
this is one
this is two
我假设实际问题比查找函数的简单字符串比较复杂,但为了清楚起见,我的第一个示例使用了简化的情况 如果将B视为可以导入的模块,使用内置的
vars()
,您可以并行地迭代函数名和函数本身,并测试条件并执行
import B
for name, value in vars(B).items():
if name == 'functionOne':
value()
vars()
是一个类似于dir()
的内置函数,只是它返回名称和值的字典。如果使用了dir()
,则必须使用getattr()
或B.\uu dict\uuu[name]
或其他额外步骤来获取值
更一般的实现可能如下所示:
for name, value in vars(B).items():
if callable(value) and check_conditions_met(name, value):
value()
您需要声明并实现检查满足的条件()
value()
调用不带参数的函数
for
循环迭代模块每个成员的名称
,及其值
<如果值可以作为函数调用,则code>callable()
将为true
如果您已经知道要在模块中执行的函数的名称,并且它们没有变化,但可能无法实现:
try:
B.functionOne()
except AttributeError as ae:
print(f"module 'B' may be missing an implementation: {ae}")
始终可以使用getattr()
按名称获取任何对象的属性:
这是一种迂回的方式。但对于使用用户输入(如另一个答案所示)来选择要运行的函数的情况可能有用:
for _ in range(n_attempts):
try:
request = input("What do you want me to do? ")
cmd, *params = request.split()
getattr(B, cmd)(*params)
except AttributeError:
print("Please try again...")
我假设实际问题比查找函数的简单字符串比较复杂,但为了清楚起见,我的第一个示例使用了简化的情况 如果将B视为可以导入的模块,使用内置的
vars()
,您可以并行地迭代函数名和函数本身,并测试条件并执行
import B
for name, value in vars(B).items():
if name == 'functionOne':
value()
vars()
是一个类似于dir()
的内置函数,只是它返回名称和值的字典。如果使用了dir()
,则必须使用getattr()
或B.\uu dict\uuu[name]
或其他额外步骤来获取值
更一般的实现可能如下所示:
for name, value in vars(B).items():
if callable(value) and check_conditions_met(name, value):
value()
您需要声明并实现检查满足的条件()
value()
调用不带参数的函数
for
循环迭代模块每个成员的名称
,及其值
<如果值可以作为函数调用,则code>callable()
将为true
如果您已经知道要在模块中执行的函数的名称,并且它们没有变化,但可能无法实现:
try:
B.functionOne()
except AttributeError as ae:
print(f"module 'B' may be missing an implementation: {ae}")
始终可以使用getattr()
按名称获取任何对象的属性:
这是一种迂回的方式。但对于使用用户输入(如另一个答案所示)来选择要运行的函数的情况可能有用:
for _ in range(n_attempts):
try:
request = input("What do you want me to do? ")
cmd, *params = request.split()
getattr(B, cmd)(*params)
except AttributeError:
print("Please try again...")
好的,大家已经发布了基于
dir()
+getattr()
或vars()
的解决方案,这些解决方案从技术上确实回答了这个问题。我只想指出,如果要执行的函数的名称来自用户输入,则使用显式允许函数的dict更安全、更清晰,即:
# b.py
def functionOne():
print("this is one")
def functionTwo():
print("this is two")
def no_you_dont():
raise Exception("you should not call me")
然后
# a.py
import b
funcs = {"name1" : b.functionOne, "name2": b.functionTwo}
name = input("which func ?")
try:
f = funcs[name]
except KeyError:
print("sorry, {} is not allowed".format(name)
else:
f()
关键是1/哪些函数应该以这种方式使用是尽可能明确的,2/你不会无意中暴露任何不应该暴露的东西。好的,每个人都已经发布了基于
dir()
+getattr()
或vars()
的解决方案,这在技术上确实回答了这个问题。我只想指出,如果要执行的函数的名称来自用户输入,则使用显式允许函数的dict更安全、更清晰,即:
# b.py
def functionOne():
print("this is one")
def functionTwo():
print("this is two")
def no_you_dont():
raise Exception("you should not call me")
然后
# a.py
import b
funcs = {"name1" : b.functionOne, "name2": b.functionTwo}
name = input("which func ?")
try:
f = funcs[name]
except KeyError:
print("sorry, {} is not allowed".format(name)
else:
f()
关键是1/哪些函数应该以这种方式使用是尽可能明确的,2/你不会无意中暴露任何不应该暴露的东西。通过创建一个函数容器?你为什么要迭代其他模块?如果你已经知道函数名,你可以直接得到它。除了精确的函数名匹配,您还需要支持其他比较吗?是否需要支持函数名以外的其他条件,例如类型?最重要的是,到目前为止你尝试了什么?你能澄清一下你想要实现什么吗?与其直接在模块上操作,不如通过