I have a Class, it will be implemented to be many instances. I want to keep connections between some of the instances, and pass messages among them. In C++, I can do this like:
class A
{
A (*connections)[];
int sum;
public:
void pass(int index)
{
connections[index] -> receive(sum);
}
void receive(int input)
{
sum += input;
}
}
Then I only need to add pointers of other instances to connections[], I can pass messages among them with each other.
Currently I have to use Python doing this, but Python doesn’t support pointers. I wonder what is the proper solution, or design pattern, to solve this problem?
Thank you in advance.
Python doesn’t need pointers in order to achieve this as every variable is a reference to an object. These references are slightly different from C++ references, in that they can be assigned to – much like pointers in C++.
So to achieve what you’re looking for, you’d just need to do something like this:
And just to prove that this works as expected:
So as you can see we have altered the original objects
a1anda2by calling through to them via the references ina3