在Python中,从类属性中获取类实例的另一个属性

时间:2013-01-25 23:35:13

标签: python python-2.7

我如何或可以做以下事情?请注意,虽然我声明了b_class,但我并不总是直接实例化b_class,而是由库实例化。

class a_class:
  def some_method(self):
    """
    get the class instance of b_class in which a_class is instantiated
    using that instance, get var1
    perform some action based on var1
    """

class b_class:
  var1 = "init by the constructor or a method"
  a_inst = a_class()
  """
  other attributes
  """

2 个答案:

答案 0 :(得分:1)

当您致电b_class或创建some_method个实例时,您不能,也不能将a_class实例的引用传递给您。

您可以在任何地方存储对该a_class实例的引用,因此,您不能在Python中从已分配它的实例方法中知道它。

所以,这样做:

class a_class:
  def __init__(self, parent):
    self.parent = parent

  def some_method(self):
    self.parent.var1

class b_class:
  def __init__(self):
      self.var1 = "init by the constructor or a method"
      self.a_inst = a_class(self)

现在a_class'的实例知道他们的父级,并且可以通过self.parent实例变量引用它们。

答案 1 :(得分:0)

让我先说一句:不要这样做;它是一个可怕的,过于复杂的hack,正确的方法是在你实例化后者时将a_class实例传递给你的b_class实例,正如Martijn很好地说明的那样。

尽管如此,假设您的每个a_class实例最多只与一个b_class实例关联,您可以通过询问垃圾收集器将其删除。

import gc

class A(object):
    def get_my_B(self):
        # iterate over objects that point to us
        for ref in gc.get_referrers(self):
            if type(ref) is dict:   # could be instance's __dict__
                instances = [x for x in gc.get_referrers(ref) if type(x) is B]
                # if we have been found in the __dict__ of exactly one instance
                # and that __dict__contains a reference to us, we found our B
                if len(instances) == 1:
                    if getattr(instances[0], "__dict__", None) is ref:
                        if ref.get("a", None) is self:
                            return instances[0]
        return None

class B(object):
    def __init__(self):
        self.a = A()

b = B()
assert b.a.get_my_B() is b