我正在解决python koans。直到 34 号,我才遇到任何真正的问题。
这就是问题:
项目:创建代理类
在这个作业中,创建一个代理类(下面为您启动一个)。您应该能够使用任何对象初始化代理对象。代理对象上调用的任何属性都应该转发给目标对象。在发送每个属性调用时,代理应该记录发送的属性的名称。
代理类已为您启动。您将需要添加一个缺少处理程序的方法和任何其他支持方法。代理类的规范在 AboutProxyObjectProject 公文中给出。
注意:这有点棘手,它是 Ruby Koans 对应物,但你可以做到!
到目前为止,这是我的解决方案:
class Proxy(object):
def __init__(self, target_object):
self._count = {}
#initialize '_obj' attribute last. Trust me on this!
self._obj = target_object
def __setattr__(self, name, value):pass
def __getattr__(self, attr):
if attr in self._count:
self._count[attr]+=1
else:
self._count[attr]=1
return getattr(self._obj, attr)
def messages(self):
return self._count.keys()
def was_called(self, attr):
if attr in self._count:
return True
else: False
def number_of_times_called(self, attr):
if attr in self._count:
return self._count[attr]
else: return False
在此测试之前它一直有效:
def test_proxy_records_messages_sent_to_tv(self):
tv = Proxy(Television())
tv.power()
tv.channel = 10
self.assertEqual(['power', 'channel='], tv.messages())
因为tv.messages()
是由代理对象而不是电视对象获取的['power']
。
我试图操纵该方法,但我总是以无限循环结束。tv.channel=10
__setattr__
编辑1:
我正在尝试这个:
def __setattr__(self, name, value):
if hasattr(self, name):
object.__setattr__(self,name,value)
else:
object.__setattr__(self._obj, name, value)
但是后来我在最后一个条目的循环中得到了这个错误:
RuntimeError: maximum recursion depth exceeded while calling a Python object
File "/home/kurojishi/programmi/python_koans/python 2/koans/about_proxy_object_project.py", line 60, in test_proxy_method_returns_wrapped_object
tv = Proxy(Television())
File "/home/kurojishi/programmi/python_koans/python 2/koans/about_proxy_object_project.py", line 25, in __init__
self._count = {}
File "/home/kurojishi/programmi/python_koans/python 2/koans/about_proxy_object_project.py", line 33, in __setattr__
object.__setattr__(self._obj, name, value)
File "/home/kurojishi/programmi/python_koans/python 2/koans/about_proxy_object_project.py", line 36, in __getattr__
if attr in self._count:
循环在__getattr__
.