【问题标题】:How to iterate through class instances?如何遍历类实例?
【发布时间】:2018-08-17 11:25:33
【问题描述】:

假设我有一个超类Spam,从它那里有很多子类。如何查看其中一个的整个运行时中的所有实例并引用它们以进行数据操作或比较?不必专门针对超类和子类,但我想提一下,以防这些类和独立类之间存在不同的方法。

这似乎是 Python 编程中一个非常核心的问题,但我找不到任何信息来回答我具体寻找的内容,很奇怪,除非我使用了错误的术语。

【问题讨论】:

  • 这个answer 可能有用
  • @smac89 啊,考虑到我希望创建许多类,weakref 确实看起来是我想要完成的正确应用。谢谢。
  • 另一个类似的问题是here

标签: python python-3.x loops oop inheritance


【解决方案1】:

您可以使用WeakSet 跟踪所有仍被引用的实例。

from weakref import WeakSet

class Spam:
    _instances = WeakSet()

    def __init__(self, *args, **kwargs):
        self._instances.add(self)

这是一个工作示例。

class SubSpam(Spam):
    pass

x = SubSpam() # Create an instance

len(Spam._instances) # 1

x = 0 # Drop reference to this instance

len(Spam._instances) # 0

要使上述方法正常工作,您需要确保在覆盖 __init__ 时始终调用超级 __init__ 方法。

class AnotherSubSpam(Spam):
    def __init__(self):
        # Do some stuff
        super().__init__()

或者,您还可以跟踪不经常被覆盖的 __new__ 方法中的实例。

class Spam:

    _instances = WeakSet()

    def __new__(cls, *args, **kwargs):
        # Create the instance
        instance = super().__new__(cls, *args, **kwargs)

        # Keep track of the instance
        cls._instances.add(instance)

        # Return the instance as __new__ would
        return instance

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2016-05-15
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多