What is Python's equivalent of Ruby's method_missing method? I tried using __getattr__ but this hook applies to fields too. I only want to intercept the method invocations. What is the Python way to do it?
What is Python's equivalent of Ruby's method_missing method? I tried using __getattr__ but this hook applies to fields too. I only want to intercept the method invocations. What is the Python way to do it?
This solution creates a Dummy object for which:
None (even if you pass parameters)methodname: defaultvalue for methods that should return a specific default valueclass Dummy:
def __init__(self, methods):
self.methods = methods
def __getattr__(self, attr):
defaultvalue = self.methods[attr] if attr in self.methods else None
return lambda *args, **kwargs: defaultvalue
def baz(self):
return 'custom'
d = Dummy({'foo': 1234})
print(d.foo()) # 1234
print(d.bar(1, 2, x=123, y=456)) # None
print(d.kjfdhgjf()) # None
print(d.baz()) # 'custom'