I want to be able to dynamically override all calls sent to methods on the parent class. So far I've only been able to do it for methods not defined in a parent class.
I.e. Given a parent class:
class A:
def foo(self):
print("foo")
def bar(self):
print("bar")
I want to create a Spy class that inherits from A will print "This is a spy" before calling any method on A, including foo.
class Spy(A):
pass # What do I do here?
s = Spy()
>>> s.foo()
This is a spy
foo
Current implementation
My current implementation of Spy is this:
class Spy(A):
def __getattr__(self, method):
print("This is a spy")
return getattr(super(A, self), method)
However, this only works for methods not defined in the parent class:
>>> s.baz()
This is a spy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __getattr__
AttributeError: 'super' object has no attribute 'baz'
When I call a method that exists already, it doesn't work:
>>> s.foo()
foo
>>> s.bar()
bar