gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:22 25 4
gpt4 key购买 nike

我利用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com