Skip to content

Python callback function in class

  • by

In Python, a callback function is a function that is passed as an argument to another function, and it gets called at some point during the execution of that function. When it comes to using callback functions within a class, you can define the callback function as a method of the class.

Here’s an example to illustrate how a callback function can be used within a class:

class MyClass:
    def __init__(self):
        pass

    def do_something(self, callback):
        # Perform some operation
        # ...

        # Call the callback function
        callback()

    def callback_function(self):
        print("Callback function called")

# Create an instance of MyClass
obj = MyClass()

# Call the method that triggers the callback, passing the callback function
obj.do_something(obj.callback_function)

Python callback function in class example

Here’s an example that demonstrates the usage of a callback function within a class in Python:

class EventProcessor:
    def __init__(self):
        self.callback = None

    def set_callback(self, callback):
        self.callback = callback

    def process_event(self, event):
        # Process the event
        # ...

        # Check if a callback function is set
        if self.callback:
            # Call the callback function, passing the event
            self.callback(event)

# Example callback function
def event_callback(event):
    print(f"Event processed: {event}")

# Create an instance of EventProcessor
processor = EventProcessor()

# Set the callback function
processor.set_callback(event_callback)

# Process an event, triggering the callback
processor.process_event("Button Clicked")

Output:

Python callback function in class

You can modify the logic of the EventProcessor class and the callback function to suit your specific requirements.

Do comment if you have any doubts or suggestions on this Python callback topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading