如何在外部类中使用同一对象?

2024-09-20 22:52:43 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们。 我有几个脚本包含不同的类,我有主脚本,我使用这些类,使他们一起工作,这一切都做得很好,直到我想在另一个脚本中使用main.py脚本中创建的对象

我不想在非主脚本中创建新对象。我想使用现有的对象,在main.py中以不同的脚本创建

我通过GPIO上的串行端口连接到GSM调制解调器,这样我就可以使用ATcommands与之“交谈”。我有powerOn.py类(我不想在这里发布),其中有一些pin设置,serial.py脚本,其中有一些方法允许我通过serialClass内的串行端口进行通信,还有我最新的丑陋的孩子gsmSMS.py脚本(我目前正在编写),其中我想有一些方法来发送sms、openSMS、listSMSs、delteSpecificSMS,deleteAllSMS等。在这些方法中,我需要从serialConnection发送()和接收(),但不需要在此sript中创建新对象

但问题是:

我的main.py脚本(嗯。。一部分):

def main():
try:
    global running
    running = True
    global atCommandLineOn
    atCommandLineOn = True
    with ooGSM.RPiToGsmPins() as modemGSM:
        with aGsmSerial.serialConnection() as serialGSM:
            if modemGSM.czyWlaczany==True:
                sms = aGsmSMS.sms(serialGSM) #THIS WHERE PROBLEM STARTS!!!!
            else:
                print("ERROR: Turn on the modem!!!")
            if atCommandLineOn==True:
                print("AT command line is ON.")
            else:
                print("AT command line is OFF.")
            while running==True:
                print("Write command:\n   :: ", end="")
                command = str(input())
                menu(command, modemGSM, serialGSM)
                time.sleep(0.5)
except OSError:
    print("asdasdfsdff")

if __name__ == "__main__":
    main()

魔法发生在menu()中,但由于它工作正常,我决定不压缩代码

这是我的连载

class serialConnection():
IDLE = 0; SENDING = 1; RECEIVING = 2;
UNKNOWN = 0; COMPLETE_OK = 1; COMPLETE_ERROR = 2; NOTCOMPLETE = 3; EMPTY = 4;

def __init__(self, devicePath="/dev/ttyAMA0", timeout=3):
    self.STATE = ["IDLE", "SENDING", "RECEIVING"]
    self.STATE_RESPONSE = ["UNKNOWN" ,"COMPLETE_OK", "COMPLETE_ERROR", "NOTCOMPLETE", "EMPTY"]
    self.mySerial = serial.Serial(devicePath)
    self.mySerial.timeout = timeout
    self.state = self.STATE[serialConnection.IDLE]

def __enter__(self):
    return self

def __exit__(self, type, value, traceback):
    self.mySerial.flushInput()
    self.mySerial.flushInput()
    self.mySerial.close()
    print("Serial connection closed")

def send(self, message, printWhatIsSent=True):
    command = message + "\r"
    if self.state==self.STATE[serialConnection.IDLE] and self.mySerial.isOpen(): #THIS IS WHERE PROGRAM STOPS
        self.responseState=self.STATE_RESPONSE[serialConnection.UNKNOWN]
        self.state = self.STATE[serialConnection.SENDING]
        messageInBytes = self.str2byte(command)
        self.mySerial.write(messageInBytes)
        self.mySerial.flushOutput()
        self.state = self.STATE[serialConnection.IDLE]
        if printWhatIsSent==True:
            print(">>>>> Command sent: " + message)
    else:
        print("!!!ERROR: Command did not send")

def str2byte(self, message):
    return bytearray(message, "ascii")

def receive(self, saveResponseToFile=True, printResponseStatus=True, printResponse=True):
    bytesToRead = self.mySerial.inWaiting()
    responseReadyToSave = "saveResponseToFile=False"
    if self.state==self.STATE[serialConnection.IDLE] and self.mySerial.isOpen():
        self.state = self.STATE[serialConnection.RECEIVING]
        while self.state==self.STATE[serialConnection.RECEIVING]:
            modemResponse = ""
            while self.mySerial.inWaiting() > 0:
                responseInBytes = self.mySerial.read(bytesToRead)
                modemResponse += self.byte2str(responseInBytes)
            self.mySerial.flushInput()
            self.state = self.STATE[serialConnection.IDLE]
            if printResponse==True:
                print("<<<<< received:")
                print(modemResponse)
    if self.lookForEndChars(modemResponse)==False:
        self.isResponseEmpty(modemResponse)
    if saveResponseToFile==True:
        responseReadyToSave = self.makeResponseReadyToSave(modemResponse)
    if printResponseStatus==True:
        if self.responseState==self.STATE_RESPONSE[serialConnection.NOTCOMPLETE]:
            print("INFO: End char is missing!!!")
            print()
        elif self.responseState==self.STATE_RESPONSE[serialConnection.EMPTY]:
            print("INFO: Response is EMPTY!!!")
            print()
        elif self.responseState==self.STATE_RESPONSE[serialConnection.UNKNOWN]:
            print("This one should never be printed!!!")
            print()
            print()
        return responseReadyToSave

再说一遍,不是全部代码

还有我的sms.py脚本: 类sms():

def __init__(self, serialGSMclass):
    self.setATE0() #AND OFC PROBLEM "GOES" HERE
    self.setSmsMessageFormat()
    self.setPrefferedSmsMessageStorage()

def setATE0(self):
    command = "ATE0"
    serialGSMclass.send(self, command) #AND HERE
    serialGSMclass.receive(self, False, True, False) #QUESTION 2!
    if serialGSMclass.responseState=="COMPLETE_OK":
        print("Set to ATE0")
    else:
        print("ERROR: Did not set ATE0!!!")

错误:“sms”对象没有属性状态

这意味着程序“认为”python的serialConnection.send()中的“self.state”不是serialConnectionObject.state,而是smsObject.state,它找不到它,因为没有。对吗?但我怎样才能让它工作呢

以及 问题2: 为什么我要把self放进send()呢?或者我不应该?现在,当我写它的时候,我想它可能会导致这个问题(因为我有点把自己从sms传递到serialConnection)!但我这么做是因为在我这样做之前: serialConnectionClass.send(命令)我有: 错误:send()缺少1个必需的位置参数:“message” 有点像send()需要的不仅仅是一个参数。但是既然send(self,command)引起了问题,send(command)也不起作用,我该如何使它起作用呢D级


Tags: pyself脚本sendtrueifdefsms
2条回答

Soebody发布了一个有效的答案,但被删除了。。对不起,我不记得你的昵称了。 我缺少的是sms.pyinit()脚本:

def __init__(self, serialConnection):
    if not serialConnection:
        raise Exception ("invalid serial connection")
    self.serialConnection = serialConnection

然后它工作得很好

哦,对不起。是你吗,朱利维科

在类sms中有(并给出)一个参数serialGSMclass。但你对他什么也没做。你应该这样做

def __init__(self, serialGSMclass):
    self.setATE0() #AND OFC PROBLEM "GOES" HERE
    self.setSmsMessageFormat()
    self.setPrefferedSmsMessageStorage()
    self.serialGSMclass = serialGSMclass

def setATE0(self):
    command = "ATE0"
    self.serialGSMclass.send(self, command) #AND HERE
    self.serialGSMclass.receive(self, False, True, False) #QUESTION 2!
    if self.serialGSMclass.responseState=="COMPLETE_OK":
        print("Set to ATE0")
    else:
        print("ERROR: Did not set ATE0!!!")

2:在类方法中,必须将self作为第一个参数来使用变量、方法。。。类实例的。如果没有self,就必须在方法定义上方写@staticmethod。但是你不能再使用类变量和方法了

示例:

class A:
   def __init__(self, a):
      self.a = a

   def print_a(self):
      print(self.a)

   @staticmethod
   def print_a_static():
      print(self.a)

   @staticmethod
   def print_a_static_2():
      print(a)

a_instance = A(2)               # a_instance is a instance of the class A now and has a variable a=2
a_instance.print_a()            # print the value of a: 2
a_instance.print_a_static()     # Exception: unknown self
a_instance.print_a_static_2()   # Exception: unknown a

相关问题 更多 >

    热门问题