python 中集合 class 属性的继承
inheritance of set class attribute in python
我正在尝试创建基本摘要 class,并使用保存所有已创建实例集的机制。
class Basic(object):
__metaclass__ = ABCMeta
allInstances = set()
def __init__(self, name):
self.allInstances.add(self)
def __del__(self):
self.allInstances.remove(self)
问题是set allInstances
保存了所有child classes的实例。我应该为每个 child class 单独添加此行,还是有办法在基本 class 中为每个 child class 创建集合?
thnx jonrsharpe,在阅读了您的评论、一些文档和文章、MyMeta class:
之后
from abc import ABCMeta
class MyMeta(ABCMeta):
def __init__(cls, name, bases, dct):
super(MyMeta, cls).__init__(name, bases, dct)
cls.allInstances = set()
parent class
from MyMeta import MyMeta
class Basic(object):
__metaclass__ = MyMeta
def __init__(self):
self.allInstances.add(self)
def __del__(self):
self.allInstances.remove(self)
另一种方式
from abc import ABCMeta, abstractmethod
class Basic(object):
__metaclass__ = ABCMeta
allInstances = None
def __init__(self):
if self.__class__.allInstances is None:
self.__class__.allInstances = set()
self.__class__.allInstances.add(self)
def __del__(self):
self.__class__.allInstances.remove(self)
我正在尝试创建基本摘要 class,并使用保存所有已创建实例集的机制。
class Basic(object):
__metaclass__ = ABCMeta
allInstances = set()
def __init__(self, name):
self.allInstances.add(self)
def __del__(self):
self.allInstances.remove(self)
问题是set allInstances
保存了所有child classes的实例。我应该为每个 child class 单独添加此行,还是有办法在基本 class 中为每个 child class 创建集合?
thnx jonrsharpe,在阅读了您的评论、一些文档和文章、MyMeta class:
之后from abc import ABCMeta
class MyMeta(ABCMeta):
def __init__(cls, name, bases, dct):
super(MyMeta, cls).__init__(name, bases, dct)
cls.allInstances = set()
parent class
from MyMeta import MyMeta
class Basic(object):
__metaclass__ = MyMeta
def __init__(self):
self.allInstances.add(self)
def __del__(self):
self.allInstances.remove(self)
另一种方式
from abc import ABCMeta, abstractmethod
class Basic(object):
__metaclass__ = ABCMeta
allInstances = None
def __init__(self):
if self.__class__.allInstances is None:
self.__class__.allInstances = set()
self.__class__.allInstances.add(self)
def __del__(self):
self.__class__.allInstances.remove(self)