python - 输入一个函数,得到“str”对象不可调用
问题描述
我正在尝试用 Python 制作一个命令提示符样式的程序。我想要一个可能运行的函数列表,然后检查列表;如果其中任何一个匹配,则获取匹配的输入并调用具有相同名称的函数。我目前收到一个"str" object is not callable
错误。
import os
import time
able_commands = ["clear", "test"]
def test():
print("worked")
def run_command(command):
command()
input_command()
def clear():
print("clearing...")
time.sleep(2)
os.system('cls')
def input_command():
command = input(os.path.abspath(os.sep) + " ")
check_if = command.lower()
if check_if in able_commands:
run_command(check_if)
elif check_if == "":
input_command()
else:
print("ERROR \nPlease specify a valid command")
input_command()
input_command()
我是 Python 的初学者。
解决方案
在 Python 中,函数是一流的对象。所以,你可以这样做:
def foo():
print('foo')
def bar():
print('bar')
# Create a dict of function name to the function object.
# This dict must be declared after your functions otherwise
# you will get a NameError exception.
funcs = {
'run_foo': foo
'run_bar': bar
}
# Select the function from the dict
f = funcs['run_foo']
# Run the selected function
f()
推荐阅读
- java - 有什么方法可以模拟其他类中的私有方法
- c# - C#/Unity - 用于位置和旋转更新的 TCP/UDP 多人游戏服务器?
- javascript - 如何在组条形图中隐藏一个特定组的条形?
- c# - 如何通过 COM 接口从 C++ 向 C# 发送 64 位整数
- ios - 当状态更改导致键盘在工作表中辞去第一响应者时,SwiftUI iOS 应用程序崩溃
- python - 在 Python 中对 JSON 文件进行排序并输出为 Excel
- elasticsearch - 如何使用 java 高级 REST 客户端 Elasticsearch 获取嵌套聚合存储桶
- sql - 有没有办法根据 Max(date) 在 postgres 中获取组的第一行
- django - Django模型+两个表上的唯一列(继承)
- python - Django Rest Framework 结合了 2 个查询