1

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.

EmmaGao8
  • 83
  • 9
  • 2
    Since `type` is a built-in function in Python, I would recommend against using `type` as an attribute and variable name. It is better use a name such as `neuron_type`. – Shabbir Khan Dec 09 '21 at 06:08
  • @ShabbirKhan there is no problem with using `type` as an attribute, it won't shadow built-in names. – juanpa.arrivillaga Dec 10 '21 at 08:02
  • @juanpa.arrivillaga, yeah, it won't. Using built-in names as attributes just seems like bad style in my opinion. This answer and the comments provide more details: https://stackoverflow.com/a/28091085/5302861 – Shabbir Khan Dec 10 '21 at 10:57

2 Answers2

2

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
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Ryan Fu
  • 349
  • 1
  • 5
  • 22
2

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()
Shabbir Khan
  • 187
  • 1
  • 8
  • I'm probably misunderstanding something, but could you please explain how this adds new information to my (already existing) answer? – Ryan Fu Dec 09 '21 at 06:05
  • 1
    Your answer was posted while I was finishing up mine. Since I had put work into writing my answer, I just decided to keep it. – Shabbir Khan Dec 09 '21 at 06:11