Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, How to "automatically" call a function/method from an instance method?

Is there a way to force an instance method in Python to call another method prior to executing?

A simple example for demonstration:

class MyClass(object):
  def __init__(self):
    pass
  def initialize(self):
    print "I'm doing some initialization"
  def myfunc(self):
    print "This is myfunc()!"

I'd like some way to have myfunc() automatically call initialize() prior to running. If I do:

obj = MyClass()
obj.myfunc()

I'd like to see the following as the output:

I'm doing some initialization 
This is myfunc()!

Without having to explicitly call initialize() within myfunc().

The reason for this is if I have many instances of "myfunc", say myfunc1, myfunc2, myfunc3, that all need to call "initialize", I'd rather have them all call initialize once in the same place, as opposed to manually calling the method each time. Is this something meta classes could do?

like image 760
blindsnowmobile Avatar asked Mar 15 '23 15:03

blindsnowmobile


1 Answers

You can use a decorator in Python. Make the decorator call the function you want before the one called. You will be able to use the decorator in all your desired functions. This is syntactic sugar.

like image 168
DevShark Avatar answered Apr 26 '23 14:04

DevShark