gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:54:47 25 4
gpt4 key购买 nike

在 python 中,我可以创建一个在实例化时可以接收任意方法调用的类吗?我读过this却无法拼凑起来

我猜它与属性查找有关。对于类 Foo:

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

类属性可以通过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

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

最佳答案

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

关于python - 我可以创建一个在 python 中接收任意方法调用的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31177629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com