Can I create an object that receives arbitrary method invocation in python? -


in python, can create class that, when instantiated, can receive arbitrary method invocation? have read this couldn't put pieces together

i guess has attribute lookup. class foo:

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

the class attribute can obtained print foo.__dict__, gives

{'__dict__': <attribute '__dict__' of 'foo' objects>, '__weakref__': <attribute '__weakref__' of 'foo' objects>, '__module__': '__main__', 'bar': <function bar @ 0x7facd91dac80>, '__doc__': none} 

so code valid

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

if call foo.somerandommethod(), attributeerror: 'foo' object has no attribute 'somerandommethod' resulted.

i want foo object receive random invocations , defaults no-op, ie.

def func():     pass 

how can achieve this? want behaviour mock object testing.

from http://rosettacode.org/wiki/respond_to_an_unknown_method_call#python

class example(object):     def foo(self):         print("this foo")     def bar(self):         print("this bar")     def __getattr__(self, name):         def method(*args):             print("tried handle unknown method " + name)             if args:                 print("it had arguments: " + str(args))         return method  example = example()  example.foo()        # prints “this foo” example.bar()        # prints “this bar” example.grill()      # prints “tried handle unknown method grill” example.ding("dong") # prints “tried handle unknown method ding”                      # prints “it had arguments: ('dong',)” 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -