Python 3.x 使用子类正确计数实例
我正在用OOP进行实验,并试图用每个类和子类的实例数实现一些类继承 我希望在class'Python 3.x 使用子类正确计数实例,python-3.x,oop,inheritance,instance,counting,Python 3.x,Oop,Inheritance,Instance,Counting,我正在用OOP进行实验,并试图用每个类和子类的实例数实现一些类继承 我希望在class'\uuu init\uuu方法中增加一个class变量,这样当我创建一个类的实例时,该类及其所有父类和祖辈类的计数都会增加 然而,在多次尝试之后,我正在努力实现这一点,同时将每个子类的计数与父类隔离开来 假设我有“Cls”、“SubCls”和“SubSubCls”类,如下所示 class Cls(): count = 0 def __init__(self): #genera
\uuu init\uuu
方法中增加一个class变量,这样当我创建一个类的实例时,该类及其所有父类和祖辈类的计数都会增加
然而,在多次尝试之后,我正在努力实现这一点,同时将每个子类的计数与父类隔离开来
假设我有“Cls”、“SubCls”和“SubSubCls”类,如下所示
class Cls():
count = 0
def __init__(self):
#general init stuff
self.__class__.count += 1
class SubCls(Cls):
pass
class SubSubCls(SubCls):
pass
我喜欢以下行为:
a = Cls()
SubSubCls.count #returns 0
SubCls.count #returns 0
Cls.count #returns 1
b = SubCls()
SubSubCls.count #returns 0
SubCls.count #returns 1
Cls.count #returns 2
c = SubSubCls()
SubSubCls.count #returns 1
SubCls.count #returns 2
Cls.count #returns 3
这样做的理由是,如果Cls类似于“实体”,SubCls是“物理实体”,SubSubCls是“树”,我创建了一个树的实例,我现在有一个树,一个物理实体,一个实体-即使它们都在一个对象中
到目前为止,我提出的最好的建议如下:
class Cls():
count = 0
def __init__(self):
#general init stuff
self.inc_count()
def inc_count(self):
Cls.count += 1
super().inc_count() #removing this avoids AttributeError but means having
# unique methods for inc_count in all SubCls level Classes
class SubCls(Cls):
count = 0
def __init__(self):
super().__init__()
#unique init stuff
def inc_count(self):
SubCls.count += 1
super().inc_count()
class SubSubCls(SubCls):
count = 0
def __init__(self):
super().__init__()
#unique init stuff
def inc_count(self):
SubSubCls.count += 1
super().inc_count()
这是正确的行为,但我觉得继承应该能够更好。我不想为每个类分别定义inc\u count()
,因为它们非常相似-我想在这里保持事物的可伸缩性
Cls
定义中的super().inc\u count()
,使用try和except或通过在Cls
上面定义MetaCls
来造成属性错误,所以我不太担心self.\u class.\u.count+=1
或类型(self)替换inc.\u count()
定义中的Cls.count+=1
,SubCls.count+=1
,以及SubSubCls.count+=1
.count+=1
,因为这只会导致多次对实例的“最低”类的计数执行操作。(即,创建SubSubCls实例将导致SubSubCls的总数增加3,并且其父类的计数保持不变)def inc_count(self):
DirectParentClassDefinedAtRunTime.count += 1
super().inc_count()