Issue
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.
Solution
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()
Answered By - warped
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.