如何从另一个类调用特定属性(PYTHON)

时间:2017-08-09 04:26:22

标签: python

Im working on the rental class now .

enter image description here

The rental class is needed for the rental object which has attributes from the other classes

enter image description here

我正在尝试使用super.init初始化其他属性

这是正确的,请指教。使用python 3.5

1 个答案:

答案 0 :(得分: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)

但是使用self来调用另一个类的def属性是一个更好的选择,可以通过“self。”在主线程上附加该属性,然后在任何类中访问它。

Python相当新,但希望这会有所帮助。

通过这个 - How would I access variables from one class to another?它会更有帮助。