【问题标题】:Sharing instance variable between classes在类之间共享实例变量
【发布时间】:2019-07-08 16:03:20
【问题描述】:

我有两个类 A 和 B,我想将 A 的实例变量共享给 B,并确保当我对 A 中的变量调用 del 时,B 不再有权访问它并且变量正确已删除。

我已经想到了 4 种不同的方法来实现这一点。

  1. 继承 - 我决定不这样做,因为 B 不是 A 的实例,并且在调用 super 时遇到问题(B 恰好是某个其他 ABC 的派生类)。 B 也没有使用 A 中定义的其他变量和方法。
  2. 嵌套类 - 我试过这个,但显然 python 嵌套类的行为不像 C++ 那样。
  3. 传递变量 - 这最初按预期工作,但是当我对 A 中的变量调用 del 时,B 仍然可以访问它,因为(我相信)它仍然具有对变量的引用
  4. 全局变量 - 我听说这是不好的做法

我知道weakref 可能有一个解决方案,但我想知道是否还有其他与程序设计有关的解决方案

class A():
    def __init__(self):
         self.var = myVar
    def func(self):
         return B(self.myVar2)
    def stop(self):
         del self.myVar
class B():
    def __init__(self, myVar)
        self.myVar2 = myVar
    # Other methods ...

上面是一个传递变量的例子。当我对 A 的实例调用 stop 时,变量没有被正确删除。

【问题讨论】:

    标签: python class-design weak-references


    【解决方案1】:

    仅使用程序设计(例如继承或嵌套类)寻找解决方案可能会很棘手且难以阅读,但很有可能。您可以使用全局变量,但这将是代码异味。话虽如此,我将在此处添加 weakref 解决方案,直到添加不同的解决方案为止。

    import weakref
    
    class A:
        def __init__(self):
            pass
        def __repr__(self):
            return "Instance of A"
    
    class B:
        """
        Wants a weak reference to an instance of A
        """
        def __init__(self, instance_of_a):
            self._a = weakref.ref(instance_of_a)
    
        @property
        def a(self):
          return self._a()
    
    
    a_inst = A()
    b_inst = B(a_inst)
    
    print(b_inst.a) # Instance of A
    del a_inst
    print(b_inst.a) # None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 2020-10-14
      相关资源
      最近更新 更多