如何在Python中实现指针?(或其他任何类似的解决方案)

Sky*_*ler 0 python pointers

我有一个类,它将被实现为许多实例.我想保持一些实例之间的连接,并在它们之间传递消息.在C++中,我可以这样做:

class A
{
   A (*connections)[];
   int sum;

public:
   void pass(int index)
   {
       connections[index] -> receive(sum);
   }
   void receive(int input)
   {
       sum += input;
   }
}
Run Code Online (Sandbox Code Playgroud)

然后我只需要添加其他实例的指针connections[],我可以互相传递消息.

目前我必须使用Python来做这件事,但Python不支持指针.我想知道解决这个问题的正确解决方案或设计模式是什么?

先感谢您.

obm*_*arg 6

Python不需要指针来实现这一点,因为每个变量都是对象的引用.这些引用与C++引用略有不同,因为它们可以被赋值 - 就像C++中的指针一样.

因此,要实现您所需要的,您只需要执行以下操作:

class A(object):
    def __init__( self, connections, sum ):
        self.connections = connections
        self.sum = sum

    def passToConnections( self, index ):
        self.connections[ index ].receive( self.sum )

    def receive( self, input ):
       self.sum += input
Run Code Online (Sandbox Code Playgroud)

并且只是为了证明这是按预期工作的:

>>> a1 = A( [], 0 )
>>> a2 = A( [], 0 )
>>> a3 = A( [ a1, a2 ], 10 )
>>> a3.passToConnections( 0 )
>>> a3.passToConnections( 1 )
>>> a3.passToConnections( 1 )
>>> print a1.sum
10
>>> print a2.sum
20
Run Code Online (Sandbox Code Playgroud)

因此,您可以看到我们已经更改了原始对象,a1a2通过引用调用它们a3