python - 重构函数内的代码重复

标签 python nuke

我想重构assign_hotkey函数,因为我不喜欢if语句中的重复代码。

代码:

n_path_i = 0
c_node_i = 1
h_key_i = 2

hotkeys = [
        ['Filter/Blur', 'Blur, size 20 label "hello world"', 'A'],
        ['Draw/LightWrap', 'LightWrap', 'B'],
        ['Draw/Grain', 'Grain2', 'X']
        ]

def assign_hotkey(n_path, c_node, h_key):
    c_node_splitted = c_node.split(',')
    if len(c_node_splitted) > 1:
        menu.addCommand(n_path, 
                        lambda: nuke.createNode(*c_node_splitted),
                        h_key)
    else:
        menu.addCommand(n_path, 
                        lambda: nuke.createNode(c_node),
                        h_key)

for i in hotkeys:
    assign_hotkey(i[n_path_i], i[c_node_i], i[h_key_i])

最佳答案

由于当您将拆分 c_node 传递给 nuke.createNode 时,您正在解压从拆分 c_node 获得的列表,因此根本没有理由为列表长度为1。

您可以更改:

if len(c_node_splitted) > 1:
    menu.addCommand(n_path, 
                    lambda: nuke.createNode(*c_node_splitted),
                    h_key)
else:
    menu.addCommand(n_path, 
                    lambda: nuke.createNode(c_node),
                    h_key)

至:

menu.addCommand(n_path, 
                lambda: nuke.createNode(*c_node_splitted),
                h_key)

关于python - 重构函数内的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52847435/

相关文章:

python - PyQt : How to expand all children in a QTreeWidget

python - 在 Python 类中使用 self(在 Nuke 中制作 GUI)

c++ - Nuke - Matrix4 相机约束锁 Z 旋转

python - hash() 函数的最小值?

python - 正确安装支持 FTS5 的 sqlite3

python - 在不逐行测试策略的情况下,针对大型 DataFrame 在 Pandas 中回测交易机器人的最佳方法?

python - The Foundry Nuke – 获取字体的文件路径

javascript - 如何用python创建highcharts格式的json结构

python - 如何取消nuke pyside中的字体阴影

python - 链接按程序创建的 2 个不同节点中的两个字段