Skip to content
Advertisement

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.

Advertisement

Answer

You can go through all of the other Neurons and execute the receive function.

For example:

def fire(self):
    for other in self.connections:
        other.receive() #and whatever other things you want

def receive(self):
    print("Signal Received!") #or whatever else you want
Advertisement