python - 在 PyCLIPS 中注册 Python 方法的装饰器

标签 python introspection clips pyclips

我利用 PyCLIPS 将 CLIPS 集成到 Python 中。 Python 方法使用 clips.RegisterPythonFunction(method, optional-name) 在 CLIPS 中注册。由于我必须注册几个函数并且希望保持代码清晰,因此我正在寻找一个装饰器来进行注册。

现在是这样做的:

class CLIPS(object):
...
    def __init__(self, data):
        self.data = data
        clips.RegisterPythonFunction(self.pyprint, "pyprint")
    def pyprint(self, value):
        print self.data, "".join(map(str, value))

这就是我想要的方式:

class CLIPS(object):
...
    def __init__(self, data):
        self.data = data
        #clips.RegisterPythonFunction(self.pyprint, "pyprint")
    @clips_callable
    def pyprint(self, value):
        print self.data, "".join(map(str, value))

它将方法的编码保留在一个地方并将它们注册。

注意:我在多处理器设置中使用它,其中 CLIPS 进程在单独的进程中运行,如下所示:

import clips
import multiprocessing

class CLIPS(object):
    def __init__(self, data):
        self.environment = clips.Environment()
        self.data = data
        clips.RegisterPythonFunction(self.pyprint, "pyprint")
        self.environment.Load("test.clp")
    def Run(self, cycles=None):
        self.environment.Reset()
        self.environment.Run()
    def pyprint(self, value):
        print self.data, "".join(map(str, value))

class CLIPSProcess(multiprocessing.Process):
    def run(self):
        p = multiprocessing.current_process()
        self.c = CLIPS("%s %s" % (p.name, p.pid))
        self.c.Run()

if __name__ == "__main__":
    p = multiprocessing.current_process()
    c = CLIPS("%s %s" % (p.name, p.pid))
    c.Run()
    # Now run CLIPS from another process
    cp = CLIPSProcess()
    cp.start()

最佳答案

这样做应该相当简单:

# mock clips for testing
class clips:
    @staticmethod
    def RegisterPythonFunction(func, name):
        print "register: ", func, name

def clips_callable(fnc):
    clips.RegisterPythonFunction(fnc, fnc.__name__)
    return fnc

@clips_callable
def test(self):
    print "test"

test()

编辑:如果在类方法上使用,它将仅注册未绑定(bind)的方法。因此,如果在没有类实例作为第一个参数的情况下调用该函数,它将无法工作。因此,这可用于注册模块级函数,但不能用于注册类方法。为此,您必须在 __init__ 中注册它们。

关于python - 在 PyCLIPS 中注册 Python 方法的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10618805/

相关文章:

python - 类型错误 : '<' not supported between instances of 'tuple' and 'str'

python - 向 Sentry 发送 Django-RQ 异常

python - 如果类有 __dict__ 变量,可以检查 obj.__dict__ 吗?

swift - 确定 Swift 类的类型

syntax-error - 有条件的情况下如何正确使用加法?片段

python - 如何使用python减少在selenium webdriver中找不到元素时的等待时间

python - 使用 OpenCV 2.3 和 Python 跟踪两种不同的颜色

ios - 在 Swift 中使用 isKindOfClass

c++ - 将 Clips 嵌入到 C 中和将 Clips 嵌入到 C++ 中的不同之处

testing - 使用多文件设置设计一个单元测试框架,用于在 CLIPS 中为 CLIPS 规则编写自定义测试