在 python 中,我想创建一个带有多个点的(类)方法,以便对 xmlrpc 方法进行测试,该方法的名称可以包含很多点。当我尝试以下操作时:
class Foo(object):
def method.with.many.dots(self):
return 42
我的语法无效。我还尝试使用更复杂的想法,例如
class Foo(object):
def __getattr__(self, attr):
print attr
对于带点的方法名称,它也不能开箱即用。任何关于如何创建一个简单的模拟对象的想法,我可以用它来做类似的事情
mock.some.test.with.many.dots()
以简单的方式在 python 代码中,无需启动 xmlrpc 服务器?
请您参考如下方法:
class Foo(object):
def __init__(self):
self._attr_path = []
def __getattr__(self, attr):
self._attr_path.append(attr)
return self
def __call__(self, *args, **kw):
print ".".join(self._attr_path)
print args, kw
del self._attr_path[:]
f = Foo()
f.a.b.c(1,2,3)
这个输出:
a.b.c
(1, 2, 3) {}
解决@Daira Hopwood 的问题:
class Bar(object):
def __init__(self, foo, attr):
self.foo = foo
self._attr_path = [attr]
def __getattr__(self, attr):
self._attr_path.append(attr)
return self
def __call__(self, *args, **kw):
print self
print args, kw
def __str__(self):
return ".".join(self._attr_path)
class Foo(object):
def __getattr__(self, attr):
return Bar(self, attr)
f = Foo()
f.a.b.c(1,2,3)
再次解决@Daira Hopwood 的问题:
class Foo(object):
def __init__(self, parent=None, name=""):
self.parent = parent
self.name = name
def __getattr__(self, attr):
return Foo(parent=self, name=attr)
def __call__(self, *args, **kw):
print self
print args, kw
def __str__(self):
nodes = []
node = self
while node.parent:
nodes.append(node)
node = node.parent
return ".".join(node.name for node in nodes[::-1])
f = Foo()
x = f.a.b
y = f.a.c
x()
y()
g = f.a
f.b
g.b.c()
