首页 > 解决方案 > 尝试将附加参数传递给切换器库会导致“'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

当我在代码中根本不包含持续时间变量时,我不会收到此错误。

标签: pythonswitch-statementnonetype

解决方案


不返回的函数,隐式返回 None。所以这:

def Default():
    print('Something went wrong :(')

与此相同:

def Default():
    print('Something went wrong :(')
    return None

这意味着您的 dictget试图这样做:

return switcher.get(direction, None)()

由于没有Noneswitcher,它返回None然后None()被执行......这是无效的,因为callable(None)=False

Default实际上需要返回合法switcher密钥或raise异常。


推荐阅读