【问题标题】:Can I create an object that receives arbitrary method invocation in python?我可以在 python 中创建一个接收任意方法调用的对象吗?
【发布时间】:2015-07-02 07:01:56
【问题描述】:

在python中,我可以创建一个在实例化时可以接收任意方法调用的类吗?我已经阅读了this,但无法将它们拼凑在一起

我猜这与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

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

【问题讨论】:

  • 如果你想模拟一个对象,为什么不使用 Mock 库呢?
  • @DanielRoseman 您的建议完全正确,我只是想了解更多python的内部工作原理。

标签: python method-invocation


【解决方案1】:

来自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',)”

【讨论】:

  • 这就是我要找的! :)
  • method 签名应该以*args, **kwargs 作为参数。
猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多