我试图真正巧妙地使用 openGL,并将所有函数及其变量按逻辑顺序存储在字典中,然后按功能顺序调用它们。
def complex_draw_square(width, height, x=0, y=0, z=0, x_angle=0, y_angle=0, z_angle=0,):
action_dict = {
glPopMatrix: "E",
glRectf: (0, 0, width, height),
glTranslatef: (0, -height, 0),
glRotatef: (x_angle, y_angle, z_angle, 1),
glTranslatef: (x, y + height, z),
glPushMatrix: "E"
}
return action_dict
问题是,当我尝试这样做时,我得到了文件
"/Users/lego90511/PycharmProjects/OpenGLDummy/opengl_shortcuts.py", line 9, in complex_draw_square
glPopMatrix: "E",
TypeError: unhashable type
无论我有哪种函数变量组合,我都会得到这个。奇怪的是我在终端中使用自定义函数尝试了这个
def sum(x,y):
return x + y
d = {sum: (1, 2)}
for f in d.keys():
print f(*d[f])
>>>3
这成功了。那么为什么另一种不起作用呢?
最佳答案
鉴于您希望项目保留其顺序,并且您有重复的键(示例中的 glTranslatef
),Python 字典不是适合此目的的数据结构。
为什么不使用列表或元组来代替:
actions = [
(glPopMatrix, "E"),
(glRectf, 0, 0, width, height),
(glTranslatef, 0, -height, 0),
(glRotatef, x_angle, y_angle, z_angle, 1),
(glTranslatef, x, y + height, z),
(glPushMatrix, "E")
]
关于opengl - 用作字典键,不可散列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19522549/