私はpython koans を解決しています。34日までは何の問題もありません。
これが問題です:
プロジェクト: プロキシ クラスを作成する
この課題では、プロキシ クラスを作成します (1 つを以下で開始します)。任意のオブジェクトでプロキシ オブジェクトを初期化できる必要があります。プロキシ オブジェクトで呼び出された属性はすべて、ターゲット オブジェクトに転送する必要があります。各属性呼び出しが送信されると、プロキシは送信された属性の名前を記録する必要があります。
プロキシ クラスが開始されます。メソッド欠落ハンドラーとその他のサポート メソッドを追加する必要があります。Proxy クラスの仕様は AboutProxyObjectProject koan に記載されています。
注: これは、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__
ます。