首页 > 解决方案 > 如何在 Python 中将 if-else 语句划分为子方法?

问题描述

我最初有这个代码部分:

def ObjectInteractionWithRightHand():
    for item in itemList:
        if (item.isCollidingOnCoords(rightHandCoords) and
                player.getItemInRightHand() is None):
            if (player.isGrasped(rightHand.z, rightElbow.z)):
                player.setItemInRightHand(item)
        elif player.getItemInRightHand() is not None and \
                player.isReleased(rightHandCoords[1], rightWristCoords[1]):
            player.setItemInRightHand(None)

我试图将 if else 语句分成两个子方法以使其更小:

def ObjectInteractionWithRightHand():
    for item in itemList:
        graspObjectWithRightHand(item)
        releaseObjectFromRightHand()

def graspObjectWithRightHand(item):
    if (item.isCollidingOnCoords(rightHandCoords) and
            player.getItemInRightHand() is None):
        if (player.isGrasped(rightHand.z, rightElbow.z)):
            player.setItemInRightHand(item)
def releaseObjectFromRightHand():
    if player.getItemInRightHand() is not None and \
            player.isReleased(rightHandCoords[1], rightWristCoords[1]):
        player.setItemInRightHand(None)

我的问题是,这段代码足够“干净”吗?我的意思是我正在迭代一个“项目”列表并调用两个方法:“graspObjectWithRightHand(item)”和“releaseObjectFromRightHand()”,但没有指示何时执行这些方法之一。我怎样才能使这个更清洁?

标签: pythonfunction

解决方案


您可以将两个第一个 if 语句合并为一个

def ObjectInteractionWithRightHand():
    for item in itemList:
        if (item.isCollidingOnCoords(rightHandCoords) and
            player.getItemInRightHand() is None and 
            player.isGrasped(rightHand.z, rightElbow.z)):
                player.setItemInRightHand(item)
        elif player.getItemInRightHand() is not None and
             player.isReleased(rightHandCoords[1], rightWristCoords[1]):
                 player.setItemInRightHand(None)

然后将条件从 if 语句中删除到它自己的函数中。elif 语句可以替换为else

def ObjectInteractionWithRightHand():
    for item in itemList:
        if (RightHandIsReady(item, player)):
            player.setItemInRightHand(item)
        else:
            player.setItemInRightHand(None)

def RightHandIsReady(item, player):
    return  item.isCollidingOnCoords(rightHandCoords) and \
            player.getItemInRightHand() is None and \
            player.isGrasped(rightHand.z, rightElbow.z)

推荐阅读