如何跟踪类实例?

如何跟踪类实例?,第1张

如何跟踪实例

跟踪实例的一种方法是使用类变量

class A(object):    instances = []    def __init__(self, foo):        self.foo = foo        A.instances.append(self)

在程序结束时,您可以像下面这样创建字典:

foo_vars = {id(instance): instance.foo for instance in A.instances}

只有一个列表:

>>> a = A(1)>>> b = A(2)>>> A.instances[<__main__.A object at 0x1004d44d0>, <__main__.A object at 0x1004d4510>]>>> id(A.instances)4299683456>>> id(a.instances)4299683456    >>> id(b.instances)4299683456


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5654710.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存