Home > front end >  Force run of specific method
Force run of specific method

Time:03-25

I'm not entirely sure how to phrase the title. Will change it if it doesn't make sense..

I recently came across method chaining and I really enjoy using it to accomplish some tasks.

Then I noticed I was calling one particular method at the end of every method and I was thinking if it's possible to force the execution of this method once the end of the chain is reached?

In fact, regardless of chaining, is it possible to do something like this with just normal class methods?

So for example:

class Alphabet:

    def _use_me(self):
        pass

    def a(self):
        # do some stuff
        self._use_me()
        return self

    def b(self):
        # do some stuff
        self._use_me()
        return self

    def c(self):
        # do some stuff
        self._use_me()
        return self

I was wondering that instead of at the end of every method to call self._use_me(), if it's possible to just run self._use_me() by default?

Maybe I am even thinking of it wrong and should change the implementation? Suggestions are welcome.

I can't find anything regarding this - but that could just be due to lack of knowledge and not using the correct search parameters on Google.

CodePudding user response:

context managers come to mind:

class Alphabet:

    def __init__(self):
        return 
    
    def __enter__(self):
        return self
    
    def __exit__(self, type, value, traceback):
        self._use_me()
        print('exit')

    
    def _use_me(self):
        print('calling _use_me')

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

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

    def c(self):
        print('c')

# calling it:
with Alphabet() as a:
    a.a()

CodePudding user response:

Yes, you use can achieve this functionality using a decorator. A decorator to decorate any/all of your functions.

Try this code:

def use_me(func):
    def wrapper(self):

        # Do some stuff, before the function
        
        func(self)

        # Do some stuff, after the function
        print("called use_me")

    return wrapper

class Alphabet:
    
    @use_me
    def a(self):
        # do some stuff
        print('calling A')

    @use_me
    def b(self):
        # do some stuff
        print('calling B')
        return self

    @use_me
    def c(self):
        # do some stuff
        print('calling B')
        return self

This is how it works:

a = Alphabet()

a.a()
# calling A
# called use_me

a.b()
# calling B
# called use_me

a.c()
# calling C
# called use_me
  • Related