2017-08-09 26 views

回答

0

不,您不需要始終進行初始化。一個類由super.init初始化一次。如果您需要從一個類訪問另一個類的屬性,可以通過使用(self。「attribute」)在主線程上使用它們。正如您在Python中所瞭解的,每個類都在單獨的線程上工作。所以基本上你需要在主線程中提供該屬性,然後調用它。

例如,這裏是我寫的多線程代碼片段。

class workerThread(QThread): 
    signal = pyqtSignal(str) 

    def __init__(self): 
     super().__init__() 
     self.abort = False 

    @pyqtSlot() 
    def run(self): 
     #print("yeah yeah ") 
     time.sleep(0.1) 
     app.processEvents() 
     self.signal.emit('Done') 

    def __del__(self): 
     #print("okay okay") 
     self.abort = True 
     self.wait() 


class General(QWidget): 

    def __init__(self): 
     super().__init__() 
     self.initUI() 
    def saveClicked(self): 
     try: 
      tex=[] 
      for edit in self.lineedits: 
       tex.append(str(edit.text())) 
      if tex[0] and tex[1] and tex[2]: 
       if ('@gmail.com' in str(tex[1])) or ('@yahoo.com' in str(tex[1])) or ('@' in str(tex[1])): 
        contact=str(tex[2]) 
        if self.validContact(contact): 
         self.workerthread = workerThread() 
         self.workerthread.signal.connect(self.savesuccess) 
         self.workerthread.start() 
        else: 
        self.workerthread = workerThread() 
        self.workerthread.signal.connect(self.errorcontactmsg) 
        self.workerthread.start() 
       else: 
        self.workerthread = workerThread() 
        self.workerthread.signal.connect(self.erroremailmsg) 
        self.workerthread.start() 
     else: 
      self.workerthread = workerThread() 
      self.workerthread.signal.connect(self.errornormmsg) 
      self.workerthread.start() 
    except: 
     self.workerthread = workerThread() 
     self.workerthread.signal.connect(self.crashingmsg) 
     self.workerthread.start() 

請參閱此鏈接完整的代碼有一個想法 - Link

或者即使你只是想初始化,然後,

class Tetrominoe(object): 
    NoShape = 0 
class Shape(object): 
    def __init__(self): 
     self.coords = [[0,0] for i in range(4)] 
     self.pieceShape = Tetrominoe.NoShape 
     self.setShape(Tetrominoe.NoShape) 

但使用自調用一類的DEF屬性在另一種情況下,更好的選擇是通過「自我」在主線程上附加該屬性,然後在任何類中訪問它。

相當新的Python,但希望這有助於。

通過這個 - How would I access variables from one class to another?它會更有幫助。

相關問題