如何在 Python 中实现指针?(或任何类似的解决方案) [英] How to implement pointers in Python? (or any similar solution else)

查看:44
本文介绍了如何在 Python 中实现指针?(或任何类似的解决方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A 类{A (*连接)[];整数总和;上市:void pass(int 索引){连接[索引] ->接收(总和);}无效接收(int输入){总和 += 输入;}}

然后我只需要将其他实例的指针添加到connections[],我就可以在它们之间相互传递消息.

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

提前致谢.

解决方案

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

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

A 类(对象):def __init__( self, connections, sum ):self.connections = 连接self.sum = sumdef passToConnections( self, index ):self.connections[ index ].receive( self.sum )def接收(自我,输入):self.sum += 输入

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

<预><代码>>>>a1 = A( [], 0 )>>>a2 = A( [], 0 )>>>a3 = A( [ a1, a2 ], 10 )>>>a3.passToConnections( 0 )>>>a3.passToConnections(1)>>>a3.passToConnections(1)>>>打印 a1.sum10>>>打印 a2.sum20

如你所见,我们已经改变了原始对象 a1a2,方法是通过 a3 中的引用调用它们>

I have a Class, it will be implemented to be many instances. I want to keep connections between some of the instances, and pass messages among them. In C++, I can do this like:

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

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

Then I only need to add pointers of other instances to connections[], I can pass messages among them with each other.

Currently I have to use Python doing this, but Python doesn't support pointers. I wonder what is the proper solution, or design pattern, to solve this problem?

Thank you in advance.

解决方案

Python doesn't need pointers in order to achieve this as every variable is a reference to an object. These references are slightly different from C++ references, in that they can be assigned to - much like pointers in C++.

So to achieve what you're looking for, you'd just need to do something like this:

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

And just to prove that this works as expected:

>>> 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

So as you can see we have altered the original objects a1 and a2 by calling through to them via the references in a3

这篇关于如何在 Python 中实现指针?(或任何类似的解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆