How to implement pointers in Python? (or any similar solution else)

六眼飞鱼酱① 提交于 2021-02-08 11:17:36

问题


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.


回答1:


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




回答2:


In Python we have names and containers (such as list) that refer to objects, similar to references in C++. Example -- a and b refer to the same object:

>>> a = object()
>>> b = a
>>> a is b
True



回答3:


Python standard way of handling things supports you. In python every variable is a reference.

class A:

    def __init__(self, name, lsum):
        self.__name = name
        self.__sum = lsum
        self.__connections = []

    def add_connection(self, con):
        self.__connections.append(con)

    def send_signal(self, cidx):
        print("Send signal from [%s] to [%s]" % 
              (self.__name, self.__connections[cidx].__name))
        self.__connections[cidx].receive(self.__sum)

    def receive(self, lsum):
        print("Add [%s] to [%s] in [%s]" % (lsum, self.__sum, self.__name))
        self.__sum += lsum

    def get_sum(self):
        return self.__sum

a = A("Obj1", 10)
b = A("Obj2", 20)
c = A("Obj3", 30)

a.add_connection(b)
a.add_connection(c)

a.send_signal(0)
a.send_signal(1)

print("Sum A [%s]" % a.get_sum())
print("Sum B [%s]" % b.get_sum())
print("Sum C [%s]" % c.get_sum())

Output:

Send signal from [Obj1] to [Obj2]
Add [10] to [20] in [Obj2]
Send signal from [Obj1] to [Obj3]
Add [10] to [30] in [Obj3]
Sum A [10]
Sum B [30]
Sum C [40]



回答4:


I'd say that you might be looking for a class attribute.

Would something like this work for you?

class A(object):
    connection = []
    def send(self, num):
        self.connection.append(num)
    def receive(self):
        return self.connection.pop(-1)

Example:

>>> x = A()
>>> y = A()
>>> x.send(10)
>>> y.receive()
10

Anyway you might want to implement this with the queue module.

Edit: I'd guess that you want the receive method to look like:

def receive(self):
    s = sum(self.connection)
    self.connection[:] = []    # empty the list
    return s

Beware that you should never assign anything to the connection attribute or you'll loose the reference.



来源:https://stackoverflow.com/questions/9821607/how-to-implement-pointers-in-python-or-any-similar-solution-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!