'How can I make Objects communicate with each other in Python?
I am making a little project for Neurons on replit.
I made a class called Neurons. I set connections = [].
I created a function called connect() to connect two Neurons via synapses.
If one neuron fires, all of the other Neurons in the connections list would receive the signal.
How could I make two different Objects in the same Class communicate with each other, so that the Neurons would know if one of their partners just fired to them?
Here is the code:
class Neuron:
def __init__(self, type='interneuron'):
self.type = type
self.connections = []
def connect(self, neuron):
self.connections.append(neuron)
def receive(self): pass
def fire(self): pass
n1 = Neuron()
n2 = Neuron('motor')
n1.connect(n2)
This link to the replit is here: https://replit.com/@EmmaGao8/Can-I-make-Neurons#main.py.
Thank you for your time and consideration.
Solution 1:[1]
When you are using the connect() method of the Neuron class to add n2 in the connections list of n1, you are creating a link between the instances.
If your print n1.connetions and n2, you would see that they point to the same object in memory. So you can define the fire() method as follows along with a receive() method:
def receive(self): pass
def fire(self):
# do something
for n in self.connections:
n.receive()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shabbir Khan |
