python - 如何创建一个在python中运行代码的变量?
问题描述
我的问题:我的目标是创建一个变量,它是一行代码,以后我可以调用该变量,而不仅仅是使用那行代码(使代码更整洁)。注释:代码中的ball_x_pos 和ball_y_pos 变化
我当前的代码:
CASE_1 = ball_y_pos + RADIUS >= WINDOW_HEIGHT # Hitting bottom floor(need to increase Y)
CASE_2 = ball_y_pos - RADIUS <= 0 # Hitting top floor(need to decrease Y)
CASE_3 = ball_x_pos + RADIUS >= WINDOW_WIDTH # Hitting right side(need to decrease X)
CASE_4 = ball_x_pos - RADIUS <= 0 # Hitting left side(need to decrease X)
if CASE_1: # Ball it hitting the bottom floor
Y_CHANGER = 1
if CASE_2: # Ball is hitting the top floor
Y_CHANGER = -1
if CASE_3: # Ball is hitting the right side
X_CHANGER = -1
if CASE_4:
X_CHANGER = 1
我认为正在发生的事情:我很确定现在代码在分配时将案例的值定义为 False。我想知道是否有任何方法我仍然可以做到这一点。提前致谢!
解决方案
我不确定我是否误解了这个问题,但您似乎正在寻找一个函数,其输出会根据输入而变化。也许这样的事情会有所帮助?
根据您在下面的评论,您希望内联您的函数以模拟宏式行为。你不能这样做,但是像 PyPy 这样的一些编译器会自动优化你的代码,所以我不会太担心。以下是可以为您解决问题的函数示例:
def CASE_1():
return ball_y_pos + RADIUS >= WINDOW_HEIGHT # Hitting bottom floor(need to increase Y)
def CASE_2():
return ball_y_pos - RADIUS <= 0 # Hitting top floor(need to decrease Y)
def CASE_3():
return ball_x_pos + RADIUS >= WINDOW_WIDTH # Hitting right side(need to decrease X)
def CASE_4():
return ball_x_pos - RADIUS <= 0 # Hitting left side(need to decrease X)
if CASE_1(): # Ball it hitting the bottom floor
Y_CHANGER = 1
if CASE_2(): # Ball is hitting the top floor
Y_CHANGER = -1
if CASE_3(): # Ball is hitting the right side
X_CHANGER = -1
if CASE_4():
X_CHANGER = 1
这定义了四个函数,每个函数在调用时都会评估其语句并根据其结果返回True
or 。False
请注意,这意味着全局变量(这是不好的做法) - 由于您还提到ball_x_pos
并ball_y_pos
在代码中进行了更改,您可能希望将变量传递进来。这样的事情会是更好的做法:
def CASE_1(y_pos):
return y_pos + RADIUS >= WINDOW_HEIGHT # Hitting bottom floor(need to increase Y)
def CASE_2(y_pos):
return y_pos - RADIUS <= 0 # Hitting top floor(need to decrease Y)
def CASE_3(x_pos):
return x_pos + RADIUS >= WINDOW_WIDTH # Hitting right side(need to decrease X)
def CASE_4(x_pos):
return x_pos - RADIUS <= 0 # Hitting left side(need to decrease X)
if CASE_1(ball_y_pos): # Ball it hitting the bottom floor
Y_CHANGER = 1
if CASE_2(ball_y_pos): # Ball is hitting the top floor
Y_CHANGER = -1
if CASE_3(ball_x_pos): # Ball is hitting the right side
X_CHANGER = -1
if CASE_4(ball_x_pos):
X_CHANGER = 1
推荐阅读
- c# - Linq 方法 - 返回包含所有选定标签的所有食谱
- c# - 在 DataGridView 中编辑单元格时 C# WPF 自动完成
- python - 为什么pyinstaller会创建这么大的exe文件?
- javascript - 径向进度条末端的圆边
- .net - 如何创建 .NET windows 应用程序来连接和调用 AS400 存储过程?
- python - 使用 python 打开 Spotify 和其他应用程序
- python - 如果以前我使用随机包在 python 中生成 unique_code,那么使用 secrets 包的最佳方法是什么?
- php - 没有安装 nwidart/laravel-menus
- java - Spring Controller 不调用 SpringMVC
- arrays - Delphi 中的移动函数支持托管数据类型