从其他方法python访问方法变量

时间:2017-02-07 21:11:43

标签: python

我在下面的代码中从closeconnection()访​​问readholdingregisters()中的client.close()时遇到问题:

class EnergyMeter:
    def __init__(self, model, gatewayipaddress, port ,deviceid):
        self.model = model
        self.gatewayipaddress = gatewayipaddress
        self.port = port
        self.deviceid = deviceid

    def readholdingregisters(self, startingregister, numberofregisters):
        from pymodbus3.client.sync import ModbusTcpClient as ModbusClient
        client = ModbusClient(self.gatewayipaddress, port=self.port)
        client.connect()
        if #some code here:
            #some other code here
            return concatResult
        else:
            return otherResult

这里我要关闭来自readholdingregisters()的连接client.connect():

    def closeconnection(self):
        EnergyMeter.readholdingregisters().client.close()??????????????????

你能为我提供一个很好的解决方案吗?

2 个答案:

答案 0 :(得分:0)

from pymodbus3.client.sync import ModbusTcpClient as ModbusClient

class EnergyMeter:
    def __init__(self, model, gatewayipaddress, port ,deviceid):
        self.model = model
        self.gatewayipaddress = gatewayipaddress
        self.port = port
        self.deviceid = deviceid
        self.client = ModbusClient(self.gatewayipaddress, port=self.port)
        self.client.connect()

    def readholdingregisters(self, startingregister, numberofregisters):
        if #some code here:
            #some other code here
            return concatResult
        else:
            return otherResult

然后,要关闭,请致电energy_meter.client.close()以查找要关闭的energy_meter

答案 1 :(得分:0)

通常的做法是,将客户端作为类的数据库。

        self.client = ModbusClient(self.gatewayipaddress, port=self.port)
        self.client.connect()
        #some code here


    def closeconnection(self):
        self.readholdingregisters()
        self.client.close()

但是,如果您想通过课程EnergyMeter.readholdingregisters()

访问方法

然后它应声明为staticmethodclassmethod,此方法应返回客户端实例。 Link