Home > OS >  How can I make Objects communicate with each other in Python?
How can I make Objects communicate with each other in Python?

Time:12-09

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.

CodePudding user response:

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

If this helps you, please accept this answer for future reference (click the check mark), and if it doesn't, please do tell.

CodePudding user response:

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()
  • Related