0

I would like to add some additional behavior to all methods in a Python class without having to define this in each method.

For example, timing every function.

class A:
    def a(self):
        print('a')

    def b(self):
        print('b')

Is there any way to modify the behavior of each method when called from an instance of class A without needing to define this in every method (preferably without the use of decorators):

class A:
    def a(self):
        s = time.time()
        print('a')
        e = time.time()
        print(f'a: {e - s}s')

    def b(self):
        s = time.time()
        print('b')
        e = time.time()
        print(f'b: {e - s}s')
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Evan Brittain
  • 547
  • 5
  • 15
  • It could be done with a metaclass. But, personally, I think it is a reasonable use-case for a decorator. – wim Aug 10 '23 at 18:04

0 Answers0