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霍普伍德的問題:
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霍普伍德的問題:
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()
Python將其評估爲mock對象'some'屬性的'test'屬性的'many'屬性的'dots'方法。 – whatyouhide 2013-03-15 10:37:31
[HYRY的解決方案](http://stackoverflow.com/a/15430170/1974792)是您需要的一個,但它不適用於'with'或任何其他關鍵字,如在您的示例中。 – dmg 2013-03-15 10:39:09