简体   繁体   English

如何让 Python 中的对象相互通信?

[英]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 .我制作了一个名为Neurons的 class 。 I set connections = [] .我设置connections = [] I created a function called connect() to connect two Neurons via synapses.我创建了一个名为connect()的 function 来通过突触连接两个神经元。 If one neuron fires, all of the other Neurons in the connections list would receive the signal.如果一个神经元触发, connections列表中的所有其他神经元都会收到信号。

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?我怎样才能使同一个 Class 中的两个不同对象相互通信,以便神经元知道他们的一个伙伴是否刚刚向他们开火?

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 .这个replit的链接在这里: https://replit.com/@EmmaGao8/Can-I-make-Neurons#main.py

Thank you for your time and consideration.感谢您的时间和考虑。

You can go through all of the other Neurons and execute the receive function.您可以通过所有其他神经元 go 并执行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.如果这对您有帮助,请接受此答案以供将来参考(单击复选标记),如果没有,请告知。

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.当您使用Neuron class 的connect()方法将n2添加到n1connections列表中时,您正在创建实例之间的链接。

If your print n1.connetions and n2 , you would see that they point to the same object in memory.如果您打印n1.connetionsn2 ,您会看到它们指向 memory 中的相同 object。 So you can define the fire() method as follows along with a receive() method:因此,您可以将fire()方法与receive()方法一起定义如下:

def receive(self): pass

def fire(self):
    # do something
    for n in self.connections:
        n.receive()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM