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

Python 如何在外部类中使用相同的对象?,python,raspberry-pi2,Python,Raspberry Pi2,嗨,伙计们。 我有几个包含不同类的脚本,我有主脚本,在主脚本中我使用这些类并使它们一起工作,所有这些都工作得很好,直到我想在另一个脚本中使用main.py脚本中创建的对象 我不想在非主脚本中创建新对象。我想使用在main.py中以不同脚本创建的现有对象 我通过GPIO上的串行端口连接到GSM调制解调器,这样我就可以使用ATcommands与之“对话”。我有powerOn.py类(我不想在这里发布),我有一些pin设置,serial.py脚本,我有一些方法,允许我通过serialClass内的串行

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

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

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

但问题是:

我的main.py脚本(嗯,是其中的一部分):

神奇发生在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”对象没有属性状态

这意味着程序“认为”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

在类
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

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

然后它工作得很好


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

这似乎太陈词滥调了。你问题的题目很简单,为什么问题这么复杂?请将问题的性质与您的实际代码分离,并向我们提供一个。sms.py和gmsSMS.py是否相同?是的,您是对的。我在init.sr中缺少self.serialGSMclass=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!!!")
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
def __init__(self, serialConnection):
    if not serialConnection:
        raise Exception ("invalid serial connection")
    self.serialConnection = serialConnection