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

时间:2016-04-08 09:27:52

标签: python raspberry-pi2

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

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

我通过GPIO上的串口连接到GSM调制解调器,所以我可以使用AT命令来"通话"它。我有powerOn.py类(我不会在这里发布)我有一些引脚设置,serial.py脚本,我有一些方法,允许我通过serialClass和我最新的丑陋孩子串口通信gsmSMS.py脚本(我目前正在处理它)我希望有一些方法来发送sys,openSMS,listSMSs,delteSpecificSMS,deleteAllSMS等。在这些方法中我需要来自serialConnection的send()和receive()但是没有在这个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()中,但由于它正常工作,我决定不打算编写代码。

这是我的serial.py

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脚本: class 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!!!")

错误:&#39;短信&#39;对象没有属性状态

这意味着程序&#34;认为&#34; &#34; self.state&#34;在serialConnection.send()for python isnt serialConnectionObject.state但是smsObject.state它找不到它,因为没有人。对?但是我怎样才能让它发挥作用呢?

和 问题2: 为什么我必须将self置于send()中?或者我不应该?现在,当我写它时,我认为它可能会导致问题(因为我有点将自己从短信传递到serialConnection)!但是我这样做是因为在我这样做之前: serialConnectionClass.send(命令),我有这个: 错误:send()缺少1个必需的位置参数:&#39; message&#39; 它有点像send()需要的不仅仅是一个参数。但是由于send(self,command)导致问题而send(命令)不起作用,我该怎么做呢? :d

2 个答案:

答案 0 :(得分:0)

在班级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

答案 1 :(得分:0)

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

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

然后它工作正常。

哦,抱歉。是你吗,julivico?