python - 尝试将附加参数传递给切换器库会导致“'NoneType' 对象不可调用”错误
问题描述
我正在尝试将两个参数传递给 switcher 函数,然后使用其中一个参数来定义 switch case,并将其中一个参数传递给 case 函数。我提供的代码部分具有其中一种情况的功能,其余的格式类似。
我不确定这是否是创建此函数的正确方法,或者我为什么会收到此错误。
right = 1
def Default():
print('Something went wrong :(')
def Right(duration):
pyautogui.moveTo(1123,899) #Right Arrow Button
pyautogui.mouseDown()
time.sleep(duration)
pyautogui.mouseUp()
time.sleep(0.03)
def Move(direction,duration):
switcher = {
1: Right(duration) ,
2: Left ,
3: Down ,
4: DiagonalUp
}
return switcher.get(direction, Default)()
x = 2.5
Move(right,x)
我得到的错误是:第 48 行,在 Move return switcher.get(direction, Default)() TypeError: 'NoneType' object is not callable
当我在代码中根本不包含持续时间变量时,我不会收到此错误。
解决方案
不返回的函数,隐式返回 None。所以这:
def Default():
print('Something went wrong :(')
与此相同:
def Default():
print('Something went wrong :(')
return None
这意味着您的 dictget
试图这样做:
return switcher.get(direction, None)()
由于没有None
键switcher
,它返回None
然后None()
被执行......这是无效的,因为callable(None)
=False
您Default
实际上需要返回合法switcher
密钥或raise
异常。
推荐阅读
- javascript - 如何从 child_process 中获取无缓冲或至少按顺序获取 stdout 和 stderr
- c - 用于最大值的调用约定。x86 系统之间的可移植性
- javascript - 自定义 JavaScript 未从浏览器执行
- java - java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder
- c++ - 具有多项选择的 wxListCtrl 给出错误的结果
- angular - Ag Grid 如何覆盖消息以显示来自服务器的错误
- amazon-web-services - AWS lambda - 从长列表/s3 读取时的最佳实践
- android - 如何使用 Gradle 将 MD5 添加到 apk 的名称中
- c# - Microsoft Graph API - 创建团队时的隐藏频道
- javascript - UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“密码”