0

我正在尝试使 pyro4 代理可索引。为了测试这一点,我从http://pythonhosted.org/Pyro4/intro.html#simple-example中获取了问候示例并对其进行了修改:

服务器:

import Pyro4

class Test(object):

    def __getitem__(self, index):
        return index

test = Test()
print test[1]
print test[100]


daemon = Pyro4.Daemon()
uri = daemon.register(test)


print("Ready. Object uri =", uri)
daemon.requestLoop()

客户:

import Pyro4

uri = input("What is the Pyro uri of the object? ").strip()

test = Pyro4.Proxy(uri)
print test.__getitem__(1)
print test.__getitem__(100)

print test[1]
print test[100]

[] 符号适用于服务器,但不适用于客户端代理。我得到:

TypeError:“代理”对象不支持索引

但是直接打电话__getitem__做工作。

4

2 回答 2

1

我自己也遇到过这个。

从我看到的源代码来看,Pyro4 并没有代理__getitem__索引符号使用的 Python 隐式调用。它确实 proxy __getattr__,这就是__getitem__直接调用该方法的原因。

但是,您可以做的是(在客户端)创建 Pyro 代理(!)的代理,该代理实现__getitem__并让所有其他方法调用通过:

class TestProxy(object):
    def __init__(self, pyroTest):
        self.pyroTest = pyroTest

    def __getattr__(self, name):
        return getattr(self.pyroTest, name)

    def __getitem__(self, item):
        return self.pyroTest.__getitem__(item)

然后您可以在 TestProxy 对象上使用索引表示法,以及以正常的 Pyro 方式调用方法。

(免责声明:这个简单的解决方案可能无法涵盖各种 Pythonic 边缘情况!)

这可能值得对 Pyro 提出增强请求。

于 2015-11-04T00:25:28.263 回答
1

虽然这可能会被添加到 Pyro 代理中,但它实际上会促进潜在的可怕执行代码。对一个对象进行索引通常是因为该对象是某种集合,并且您可能正在对其进行迭代。在 Pyro 代理上这样做会导致糟糕的性能,因为每次索引查找都是远程调用。使用一个远程调用一次简单地获取要迭代的集合,然后像往常一样迭代生成的本地对象,通常会更快、更有效。YMMV,当然要视情况而定。

于 2015-11-13T23:35:41.393 回答