Search code examples
pythonpython-3.xinheritanceeventspython-class

Python events & triggers


Is there a way to trigger CHILD objects in Python? So what I mean:

class A(object):
  def a(self):
    print("Hello from A")
    # ???

class B(A)
  def b(self):
    print("Now in B")

and I need to trigger the b() function from class A, and A only "knows" that B class extends to it

I want to use it for events in something like plugins, so there will be some modules with classes which extends main class, from which I'll trigger events in plugins


Solution

  • You can define an abstract plugin type as an interface for which function can be called:

    class AbstractPlugin(object):
      def trigger(self):
        pass
    
    class APlugin(AbstractPlugin):
      def trigger(self):
        print("This is plugin A")
    
    class BPlugin(AbstractPlugin):
      def trigger(self):
        print("This is plugin B")
    

    With your class A, you could do stuff like this:

    class A(object):
      def a(self, plugin: AbstractPlugin):
        print("Hello from A")
        plugin.trigger()
    
    master = A()
    plugin_a = APlugin()
    plugin_b = BPlugin()
    
    master.a(plugin_a)
    master.a(plugin_b)
    

    This will result in:

    Hello from A
    This is plugin A
    Hello from A
    This is plugin B