简体   繁体   English

跨类的实例共享

[英]Instance sharing across classes

I have this python script which has a listener class and a main class.我有这个 python 脚本,它有一个监听器类和一个主类。 A serial stream is created in the main class and a listener instance is created in the main class.在主类中创建一个串行流,并在主类中创建一个监听器实例。 The whole purpose of the listener is to send a message on the serial port when a listened property has changed.侦听器的全部目的是在侦听的属性发生更改时在串行端口上发送消息。 The problem is that the listener doesn't have access to the output stream created in the main class.问题是侦听器无权访问在主类中创建的输出流。 The listener does an abrupt return when trying to execute the outputStream.write statement How can I give the listener access to the output stream?尝试执行outputStream.write语句时,侦听器突然返回 如何让侦听器访问输出流?

import purejavacomm
import java.beansSensorListener

class MyListener(java.beans.PropertyChangeListener):
  def propertyChange(self, event):
    if (< some property has changed >) :
        self.outputStream.write(message) # send notice on serial port
    return


class MainClass(jmri.jmrit.automat.AbstractAutomaton) :
    def __init__(self) :
        self.portID = purejavacomm.CommPortIdentifier.getPortIdentifier("COM3")
        self.port = self.portID.open("SerialCom", 50)
        self.outputStream = self.port.getOutputStream()
        return

    def init(self) :
        myListener = MyListener()
        deviceList = devices.getNamedBeanSet()

        for device in deviceList :
            device.addPropertyChangeListener(myListener)
        return

a = MainClass()
a.start();

It seems that really MyListener should either have a stream passed into the constructor or the callback (using lambda expression).似乎真的MyListener应该将流传递给构造函数或回调(使用lambda表达式)。

First, which is probably the cleanest way, would look like this:首先,这可能是最干净的方式,如下所示:

def init(self) :
        myListener = MyListener(self.outputStream)

Second version: device.addPropertyChangeListener(lambda x: myListener(x, self.outputStream)) Both need changes in the MyListener class to either constructor, or definition of propertyChange .第二个版本: device.addPropertyChangeListener(lambda x: myListener(x, self.outputStream))两者都需要在MyListener类中对构造函数或propertyChange的定义进行更改。

If you are set of sharing an instance of here are two options.如果您要设置共享实例,这里有两个选项。

If you can modify arguments to MyListener constructor you pass in instance of MainClass to it:如果您可以修改MyListener构造函数的参数,则将MainClass的实例传递给它:

def init(self) :
        myListener = MyListener(self)

If not, a little bit more hacky way of doing this is by making MainClass a singelton (see example here ), and then calling it's constructor within MyListener如果不是,那么更老套的方法是让MainClass成为一个单例(参见这里的示例),然后在MyListener中调用它的构造函数

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

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