Skip to main content
 首页 » 编程设计

python之从另一个类中删除一个对象

2024年10月24日9kerrycode

我创建了两个不同的类,我需要从一个类中删除另一个类中的对象。

这是部分代码:

class A(self): 
  def __init__: 
    #Some stuff in here 
 
    self.splitter = QSplitter(Qt.Vertical) 
 
  def createObject(self): 
    plot = Matplotlist()     #This is a matplotlib figure 
    self.splitter.addwidget(plot) 
 
class B(self): 
  def __init__(self): 
    #Some stuff in here 
 
  def deleteObject(self): 
    delete_splitter = ????????? 

如何从类 B 访问类 A 中的 self.splitter?

请您参考如下方法:

我在评论中的意思是这样的:

给定两个类 A、B,其中 class A 有一个 __init__ 方法分配一个属性 val 到从该类创建的实例:

class A(object): 
 
    def __init__(self, val): 
        self.val = val  # assign val to instance variable 
 
    # other methods defined here.. 

class B 可以定义一个方法 deleteObject,该方法采用 argument 作为 class 的 instance A 并删除其中包含的属性(即 val):

class B(object): 
 
    def __init__(self): 
        # initialize things 
 
    def deleteObject(self, obj): 
        # delete the attribute 'val' from object 
        del object.val 

您可以通过实例化 class A 和指定的 val 来使用此方法:

a = A("value") 
a.val  # prints value 

然后将实例传递给 B 实例的方法 deleteObject:

b = B() 
b.deleteObject(a) 

现在,如果您尝试访问 a.val,您将得到一个 AttributeError,表明该实例没有名称为 val 的属性;它已被删除:

a.val 
--------------------------------------------------------------------------- 
AttributeError                            Traceback (most recent call last) 
<ipython-input-20-eef8eac9d06d> in <module>() 
----> 1 a.val 
 
AttributeError: 'A' object has no attribute 'val'