Skip to content
Advertisement

Python: Using property get/set to run on sub-class function

I have a setup that looks something like this simplified setup:

class WorkerBee():
   def __init__(self):
      self.x = 1
      self.old_x = None
   def update_x(self, val):
      self.update_old_x()
      self.x = val

   def _update_old_x(self):
      self.old_x = self.x

class MainClass():
    def __init__(self):
      self.bee = WorkerBee()

    def updated_WorkerBee(self):
      print('yay, it was updated')

I understand the use of @property to do a get – set setup for an attribute. But in this case, I’m trying to figure out how I can directly call the WorkerBee methods (there are more than 1 in my case….) that would also trigger MainClass.updated_WorkerBee()

In:
main = MainClass()
main.bee.update_x(2)  

Out:
yay, it was updated

Any help is appreciated!

Advertisement

Answer

You could add a reference to the main object to the bee, like a parent:

class WorkerBee:
    def __init__(self, main):
        self.main = main
        self.x = 1
        (...)

and then use it in your update methods within WorkerBee, to update main too:

 def update_x(self, val):
     self.update_old_x()
     self.x = val
     self.main.updated_WorkerBee()

To do that, pass the main to the bee when you create it:

class MainClass:
    def __init__(self):
        self.bee = WorkerBee(self)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement