从json,python创建动态函数

时间:2014-05-22 16:44:51

标签: python-2.7

我是python的新手,我需要从以下json中动态创建类:

{
    "name": "ICallback",
    "functions": [
        {
            "name": "OnNavigation", 
            "parameters": [
                {"name":"Type", "type": "int", "value": "0"},
                {"name":"source", "type": "int", "value": "0"},
                {"name":"tabId", "type": "string", "value": ""},
                {"name":"Url", "type": "string", "value": ""},
                {"name":"Context", "type": "int", "value": "0"}
            ]
        }
    ]
}

我找到了如何创建课程,但我不了解如何动态创建方法。 现在,函数只会引发NotImplemented异常。

1 个答案:

答案 0 :(得分:1)

所以你已经知道要创建一个类:

class Void(object):
    pass

kls = Void()

您想要从JSON创建一个方法,但我将从可以从JSON创建的字符串中创建它:

from types import MethodType

d = {}
exec "def OnNavigation(self, param): return param" in d

kls.OnNavigation = MethodType(d["OnNavigation"], kls)
# setattr(kls, "OnNavigation", MethodType(d["OnNavigation"], kls))

print kls.OnNavigation("test")

应输出 test