在python中从另一个类创建一个类对象

时间:2016-02-04 13:32:37

标签: python class object pyqt

我是python中的新手,我试图在一个类中创建一个对象,然后从另一个类中删除该对象。

这是代码的一部分:

class Win(QMainWindow):
 list_1 = []              #This lists are filled with objects
 list_2 = []
 def __init__(self):
   #A lot of stuff in here

   self.splitter = QSplitter(Qt.Vertical)

 def addObject(self):
   plot = Matplotlib()     #This is another class where i create a matplotlib figure   
   if len(Win.list_1) < 2:
     self.splitter.addWidget(plot)

所以,有了这个,我创建一个对象,如果list_1中的项目数低于3,然后我将它添加到list_1和list_2,我当然将它添加到拆分器。这很好用。现在,我创建了一个删除此拆分器的方法(其中包含对象),如下所示:

  deleteObject(self):
    if len(Win.list_1) == 1:
      widget_erased = self.splitter.widget(index)
      widget_erased.hide()
      widget_erased.deleteLater()

如你所见,如果我有一个对象,我可以删除它。当我有更多的对象时,问题就来了。在这个方法中,我写道:

    if len(Win.list_1) > 1:
    #I open A QDialog where i see the names of the objects from the lists in a QListWidget
      self.delete = Delete()      
      self.delete.exec_()

现在,这是QDialog的类:

class Delete(self):
  def _init__(self):
    #A lot of stuff in here

  def deleteObjectCreated(self):
    #There are another things before the next lines

    widget_erased = Win.splitter.widget(index)   
    widget_erased.hide()
    widget_erased.deleteLater()

使用这最后一个方法,我在QDialog中选择对象,当我按下一个按钮时,该对象将从两个列表中删除,但拆分器仍然存在,我收到此错误:

type object "Win" has no attribute "splitter"

我怎样才能做到这一点?我的意思是,删除我从QDialog中选择的对象,即在另一个类中创建的对象?

希望你能帮助我。

2 个答案:

答案 0 :(得分:1)

问题是您尝试通过对象而不是实例对象访问splitter

在您的示例中,可以通过将实例对象(即self)设置为Delete对话框的父级来解决此问题:

class Win(QMainWindow):
    ...

    def deleteObject(self):
        ...
        if len(self.list_1) > 1:
            self.delete = Delete(self) # set self as the parent


class Delete(self):
    def _init__(self, parent):
        super(Delete, self).__init__(parent)
        ...

    def deleteObjectCreated(self):
        widget_erased = self.parent().splitter.widget(index)
        ...

答案 1 :(得分:0)

'Win'是类对象,此对象没有'splitter'属性。如果我引用类'Win'的 init ,看起来splitter是'Win'实例的属性而不是'Win'类的属性

self.splitter.QSplitter(Qt.Vertical) 

因此,当您尝试访问Win.splitter时,您正确地收到错误。

这应该是你的设计的一部分,分割器应该是实例属性或类属性,我不建议你的设计有任何东西。但只是为了处理您的代码如果您想访问Win.splitter,请执行以下更改: -

def __init__(self):
   #A lot of stuff in here

   Win.splitter.QSplitter(Qt.Vertical)

或者您可以更改def deleteObjectCreated(self),如下所示: -

def deleteObjectCreated(self, instance_win):
    instance_win.splitter.QSplitter(Qt.Vertical)