【发布时间】:2019-11-17 00:21:44
【问题描述】:
我需要跟踪某些类的实例(并对这些类做其他事情)。我希望不必在相关类中声明任何额外代码,因此理想情况下,所有内容都应在元类中处理。
我不知道如何为这些类的每个新实例添加弱引用。例如:
class Parallelizable(type):
def __new__(cls, name, bases, attr):
meta = super().__new__(cls, name, bases, attr)
# storing the instances in this WeakSet
meta._instances = weakref.WeakSet()
return meta
@property
def instances(cls):
return [x for x in cls._instances]
class Foo(metaclass=Parallelizable)
def __init__(self, name):
super().__init__()
self.name = name
# I would like to avoid having to do that - instead have the metaclass manage it somehow
self._instances.add(self)
有什么想法吗?我似乎无法在元类方面找到一个钩子来进入 Foo 的 __init__....
【问题讨论】:
标签: python python-3.x metaclass