-1

I have this class :

class DieKlass:
    #My attempt using __init__
    def __init__(self): 
        aMethod()


    def hello(self):
        print ("Hello !")

#Some other file
 Def aMethod():
     print ("me !")

and I want it to result as this on "ob" being instance of DieKlass :

ob.hello()

result in :

me !
Hello !

How to call aMethod() on every method call of DieKlass object without calling explicitly aMethod in DieKlass methods bodies ?

Anerty
  • 81
  • 1
  • 1
  • 9
  • You could hook into [`__getattribute__`](https://docs.python.org/3/reference/datamodel.html#object.__getattribute__). – jonrsharpe Oct 07 '19 at 14:17
  • 2
    Write a decorator that calls the function, then decorate every method of the class: https://stackoverflow.com/questions/6307761/how-to-decorate-all-functions-of-a-class-without-typing-it-over-and-over-for-eac – Patrick Haugh Oct 07 '19 at 14:21
  • @PatrickHaugh This will work, thank you – Anerty Oct 07 '19 at 14:26
  • @jonrsharpe this only works for attribute, not methods calls ... still, thank you – Anerty Oct 07 '19 at 14:26
  • 1
    Accessing a method is exactly the same as accessing any other attribute, you can return a wrapper the consumer calls through. – jonrsharpe Oct 07 '19 at 14:46

1 Answers1

2
def aMethod(func):
    def function_wrapper(x):
        print("Me")
        func(x)
    return function_wrapper

class DieKlass:
    @aMethod
    def hello(self):
        print("Hello")

More you can find here: https://www.python-course.eu/python3_decorators.php

QbA
  • 48
  • 2