python - 获取类中特定类型的所有实例
问题描述
有没有办法在 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
对象,但我不想要任何其他属性或方法。
解决方案
您可以非常轻松地使用类变量:
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
推荐阅读
- mysql - 来自 SQLIte3 集成的 MYSQL 查询错误
- java - 使用 7 个线程生成无限的数字序列
- reactjs - Create-react-app 推送到 Heroku 错误“推送被拒绝,无法编译 Node.js 应用程序。”
- android - 如何在导航视图中更改矢量图像的颜色
- ios - 上次单击时如何使按钮 UIButton 保存
- reactjs - React 渲染如何改变道具
- html - rST 渲染问题:文本没有在侧边栏周围流动
- aframe - A-Frame:光标在 VR 中是固定不动的
- reactjs - 向数组 React 添加新元素时的无限循环
- php - 我的 Datepicker 系统有问题(禁用日期)