如何在外部 class 中使用相同的 object?

How can I use the same object in an external class?

大家好。 我有几个包含不同 classes 的脚本,我有主脚本,我在其中使用这些 classes 并使它们一起工作,并且一切正常,直到我想使用 object 创建于main.py 另一个脚本中的脚本。

我不想在我的 not-main 脚本中创建新的 object。我想在不同的脚本中使用在 main.py 中创建的现有 object。

我通过 GPIO 上的串行端口连接到 GSM 调制解调器,因此我可以使用 AT 命令 "talk" 连接到它。我有 powerOn.py class(我不会在这里 post),我有一些 pin 设置,serial.py 脚本,我有一些方法可以通过serialClass 中的串行端口和我最新的丑陋 child gsmSMS.py 脚本(我目前正在处理它),我想在其中使用一些方法来发送 SMS、openSMS、listSMSs、delteSpecificSMS、deleteAllSMS 等。在里面我需要 serialConnection 中的 send() 和 receive() 方法,但无需在此脚本中创建新的 object。

但问题来了:

我的 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 短信():

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' object 没有属性状态

这意味着程序 "thinks" serialConnection.send() 中的 "self.state" for python 不是 serialConnectionObject.state 而是 smsObject.state 并且找不到因为没有人。正确的?但是我怎样才能让它发挥作用呢?

并且 问题2: 为什么我必须将自己放入 send() 中?或者我不应该?现在,当我写它时,我认为它可能会导致问题(因为我有点将 self 从 sms 传递到 serialConnection)!但是我这样做是因为在我拥有它之前: serialConnectionClass.send(command) 我有这个: 错误:send() 缺少 1 个必需的位置参数:'message' 有点像 send() 需要的不仅仅是一个参数。但是由于 send(self, command) 导致了问题并且 send(command) 也不起作用,我该如何使它起作用? :D

在 Class 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:在class方法中你必须把self作为第一个参数来使用class实例的变量,方法,...。没有 self 你必须在方法定义上面写 @staticmethod 。但是您不能再使用 class 变量和方法了。

示例:

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

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

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

然后它运行良好。

哦,对不起。是你吗,julivico?