我正在使用exec()语句设置一个值,如下所示:
foo = 3
def return_4():
return 4
instruction = 'foo = return_4()'
exec(instruction) # <---- WHERE THE MAGIC HAPPENS
print(foo)
Run Code Online (Sandbox Code Playgroud)
正如我所料,这是4.
我的程序有操作Rubik的立方体的操作.在这个精简版中,我会做四件事:
我将实例化一个立方体,填充一个面(缩写为"前左上"和"前右下"等).
我将有一个旋转前脸的功能.
我将有一个'解释器'函数,它接受一个多维数据集和一个指令列表,并将这些指令应用于多维数据集,返回修改后的多维数据集.这是我使用'exec'的地方(以及我认为破损发生的地方).
最后,我将在部分立方体上运行解释器,并指示旋转面部一次.
+
my_cube = [['FTL', 'FTM', 'FTR',
'FML', 'FMM', 'FMR',
'FBL', 'FBM', 'FBR'],
[],[],[],[],[]] # other faces specified in actual code
def rotate_front(cube):
front = cube[0]
new_front = [front[6],front[3],front[0],
front[7],front[4],front[1],
front[8],front[5],front[2]]
# ...
ret_cube = cube
ret_cube[0] = new_front
# pdb says we are returning a correctly rotated cube,
# and calling this directly …Run Code Online (Sandbox Code Playgroud)