我可以创建一个在python中接收任意方法调用的对象吗?

use*_*759 1 python method-invocation

在python中,我可以创建一个Class,在实例化时,可以接收任意方法调用吗?我已经读过这篇文章,但无法将这些文章放在一起

我想这与它有关attribute lookup.对于一个类Foo:

class Foo(object):
  def bar(self, a):
    print a
Run Code Online (Sandbox Code Playgroud)

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}
Run Code Online (Sandbox Code Playgroud)

所以这段代码是有效的

foo = Foo()
foo.bar("xxx")
Run Code Online (Sandbox Code Playgroud)

如果我打电话foo.someRandomMethod(),AttributeError: 'Foo' object has no attribute 'someRandomMethod'就会结果.

我希望foo对象接收任何随机调用,默认为no-op,即.

def func():
    pass
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我希望这种行为模拟一个对象进行测试.

小智 5

来自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',)”
Run Code Online (Sandbox Code Playgroud)

  • `method` 签名应该以 `*args, **kwargs` 作为参数。 (2认同)