opengl - 用作字典键,不可散列类型

标签 opengl python-2.7 dictionary function-pointers

我试图真正巧妙地使用 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/

相关文章:

c++ - 无法将法线添加到 .obj 网格

c++ - 从 QGLWidget 转移到 QWindow

opengl - 了解 glVertexAttribPointer?

python - 对于 X 轴中的字符串值,堆叠直方图失败

c - opengl中的平滑着色

python - 在 Python 2.7 中打印带反斜杠的字符串

python - 如何将函数调用添加到列表?

linq - 字典查找 (O(1)) 与 Linq 其中

c++ - 用小于迭代器之间的比较遍历 std::map

c# - 序列化字典<string, object>