python - 如何在 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()”,但没有指示何时执行这些方法之一。我怎样才能使这个更清洁?
解决方案
您可以将两个第一个 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)
推荐阅读
- php - 在块中渲染奏鸣曲管理员列表
- java - Jaspersonf iReport 子报表填充了 arraylist 作为主报表中的参数,超过 1 页会导致 java.lang.StackOverflowError,
- javascript - 将日期与字符串 javascript 进行比较
- c++ - Crypto++ SelfTestFailure 异常 - 不能使用任何库代码
- android - Flutter:每次应用显示时运行一个函数并强制小部件同时加载
- php - 仅使用简单的 html dom 找到第一个表
- java - 使用 bouncycastle jar 随机加密/解密有时有效,有时无效
- python - 我无法列出包含不同图像的文件夹的内容
- c++ - 当两个类相互依赖时,C ++如何解决类不完整类型
- flutter - 电子邮件验证状态不会变为真,除非在我做热重载的 vscode 中