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

2024-10-02 18:14:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,我可以创建一个类,当实例化时,可以接收任意方法调用吗?我读过this,但不能把它们拼凑起来

我想这和attribute lookup有关。对于类Foo

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

class属性可以通过print Foo.__dict__获得,它给出了

^{pr2}$

所以这个代码是有效的

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

如果我调用foo.someRandomMethod()AttributeError: 'Foo' object has no attribute 'someRandomMethod'将产生。在

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

def func():
    pass

我怎样才能做到这一点?我想用这个行为来模拟一个测试对象。在


Tags: 对象实例方法noobjectfoodefbar
1条回答
网友
1楼 · 发布于 2024-10-02 18:14:43

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

相关问题 更多 >