首页 > 解决方案 > 获取类中特定类型的所有实例

问题描述

有没有办法在 python 中获取一个列表或返回一个类中一个类的所有实例?我已经对其进行了一些研究,并且我看到的所有答案都假设实例是全局变量,而不是现有类的一部分。

例如,我可以找到Bar在下面的类中实例化的所有实例Foo吗?

class Foo:
   def __init__(self):
      self.mymsg1 = Bar('John Doe')
      self.mymsg2 = Bar('Jane Doe')
      self.somenumber = 42
      self.somewords = 'hello world'

class Bar:
   def __init__(self, name):
      self.hellomsg = 'hello ' + name

我希望能够得到mymsg1并且mymsg2因为它们是Bar对象,但我不想要任何其他属性或方法。

标签: pythonclass

解决方案


您可以非常轻松地使用类变量:

class Foo:
   def __init__(self):
      self.mymsg1 = Bar('John Doe')
      self.mymsg2 = Bar('Jane Doe')
      self.somenumber = 42
      self.somewords = 'hello world'

class Bar:
   _instances = []
   def __init__(self, name):
      Bar._instances.append(self)
      self.hellomsg = 'hello ' + name

>>> f = Foo()
>>> print('first:', Bar._instances[0].hellomsg,
...       ', second:' ,Bar._instances[1].hellomsg)                                                          
first: hello John Doe , second: hello Jane Doe

要通过实例化器对 Bar 实例进行分区,可以这样做:

from collections import defaultdict

class Foo:
   def __init__(self):
      self.mymsg1 = Bar('John Doe', self)
      self.mymsg2 = Bar('Jane Doe', self)
      self.somenumber = 42
      self.somewords = 'hello world'

class Bar:
   _instances = defaultdict(list)
   def __init__(self, name, instantiator):
      Bar._instances[instantiator].append(self)
      self.hellomsg = 'hello ' + name

>>> f, ff = Foo(), Foo()
>>> print('first:', Bar._instances[f][0].hellomsg,
...       ', second:' ,Bar._instances[ff][1].hellomsg)                                                          
first: hello John Doe , second: hello Jane Doe

推荐阅读