2

Python で、インスタンス化されたときに任意のメソッド呼び出しを受け取ることができるクラスを作成できますか? 私はこれを読んだが、断片をまとめることができなかった

と何か関係があると思われますattribute lookup。クラスの場合Foo:

class Foo(object):
  def bar(self, a):
    print a

class 属性は で取得できますprint Foo.__dict__

{'__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__module__': '__main__', 'bar': <function bar at 0x7facd91dac80>, '__doc__': None}

したがって、このコードは有効です

foo = Foo()
foo.bar("xxx")

を呼び出すとfoo.someRandomMethod()AttributeError: 'Foo' object has no attribute 'someRandomMethod'結果が得られます。

fooオブジェクトがランダムな呼び出しを受け取り、デフォルトで何もしないようにしたい。

def func():
    pass

どうすればこれを達成できますか?この動作で、テスト用のオブジェクトをモックしたいと考えています。

4

1 に答える 1

8

http://rosettacode.org/wiki/Respond_to_an_unknown_method_call#Pythonから

class Example(object):
    def foo(self):
        print("this is foo")
    def bar(self):
        print("this is bar")
    def __getattr__(self, name):
        def method(*args):
            print("tried to handle unknown method " + name)
            if args:
                print("it had arguments: " + str(args))
        return method

example = Example()

example.foo()        # prints “this is foo”
example.bar()        # prints “this is bar”
example.grill()      # prints “tried to handle unknown method grill”
example.ding("dong") # prints “tried to handle unknown method ding”
                     # prints “it had arguments: ('dong',)”
于 2015-07-02T07:07:49.277 に答える