I have a setup that looks something like this simplified setup:
JavaScript
x
18
18
1
class WorkerBee():
2
def __init__(self):
3
self.x = 1
4
self.old_x = None
5
def update_x(self, val):
6
self.update_old_x()
7
self.x = val
8
9
def _update_old_x(self):
10
self.old_x = self.x
11
12
class MainClass():
13
def __init__(self):
14
self.bee = WorkerBee()
15
16
def updated_WorkerBee(self):
17
print('yay, it was updated')
18
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()
JavaScript
1
7
1
In:
2
main = MainClass()
3
main.bee.update_x(2)
4
5
Out:
6
yay, it was updated
7
Any help is appreciated!
Advertisement
Answer
You could add a reference to the main object to the bee, like a parent:
JavaScript
1
6
1
class WorkerBee:
2
def __init__(self, main):
3
self.main = main
4
self.x = 1
5
( )
6
and then use it in your update methods within WorkerBee, to update main too:
JavaScript
1
5
1
def update_x(self, val):
2
self.update_old_x()
3
self.x = val
4
self.main.updated_WorkerBee()
5
To do that, pass the main to the bee when you create it:
JavaScript
1
4
1
class MainClass:
2
def __init__(self):
3
self.bee = WorkerBee(self)
4