Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading