我正在阅读blog post有关在python中覆盖__new__的示例。但是,我不理解以下示例:

class LimitedInstances(object):
    _instances = []  # Keep track of instance reference
    limit = 5

def __new__(cls, *args, **kwargs):
    if not len(cls._instances) <= cls.limit:
        raise RuntimeError, "Count not create instance. Limit %s reached" % cls.limit
    instance = object.__new__(cls, *args, **kwargs)
    cls._instances.append(instance)
    return instance

def __del__(self):
    # Remove instance from _instances
    self._instance.remove(self)


不会调用object.__new__(cls, *args, **kwargs)导致无限递归吗?另外,我看到了__new__ actually happens before an object exists。那么到底什么存储在cls中呢?

最佳答案

object.__new__中调用LimitedInstances.__new__不会导致无限递归,因为它们是不同的函数,并且object.__new__不会回调到LimitedInstances.__new__。通话费用看起来像:

LimitedInstances()
    LimitedInstances.__new__(LimitedInstances)
        object.__new__(LimitedInstances)
    object.__init__(instance) # (as there is not LimitedInstances.__init__)


它可能会比这复杂一些,但是总的来说,这就是您调用类时发生的情况。

关于python - 通过覆盖python中的__new__来限制实例总数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54438238/

10-12 22:51
查看更多