请注意,以上两个答案都是正确的,但它们有很大的不同。不仅在您编写它们的方式上,而且在最终结果中。
如果您从 baseMENUS 类派生,就会出现差异。
在 n.m. 的解决方案中,计数器对于从 baseMENUS 派生的任何类的所有实例都是相同的。另一方面,在 ThiefMaster 的情况下;每个从 baseMENUS 派生的不同类都会有计数器。
在下面的示例中。我从 baseMENUS 派生了两个类。它们是 AMENUS 和 BMENUS;我创建了 3 个 AMENUS 实例和 4 个 BMENUS 实例。
当我使用n.m的方法时,计数器一直到7。
当我使用 ThiefMaster's 时,我创建了 2 个指示物。一个到 3,另一个到 4:
class baseMENUS:
"""A class used to display a Menu"""
iMenuNumber = 0
jMenuNumber = 0
def __init__ (self):
baseMENUS.iMenuNumber = baseMENUS.iMenuNumber + 1
self.__class__.jMenuNumber = self.__class__.jMenuNumber + 1
self.counterNAMEOFCLASS = baseMENUS.iMenuNumber
self.counterclass = self.__class__.jMenuNumber
class AMENUS(baseMENUS):
def __init__(self, ):
super(AMENUS, self).__init__()
class BMENUS(baseMENUS):
def __init__(self, ):
super(BMENUS, self).__init__()
allmenus = [AMENUS() for i in range(0,3)] + [BMENUS() for i in range(0,4)]
[print('Counting using n.m. method:', i.counterNAMEOFCLASS, '. And counting using ThiefMaster method :', i.counterclass) for i in allmenus]
创建的输出是:
Counting using n.m. method: 1 . And counting using ThiefMaster method : 1
Counting using n.m. method: 2 . And counting using ThiefMaster method : 2
Counting using n.m. method: 3 . And counting using ThiefMaster method : 3
Counting using n.m. method: 4 . And counting using ThiefMaster method : 1
Counting using n.m. method: 5 . And counting using ThiefMaster method : 2
Counting using n.m. method: 6 . And counting using ThiefMaster method : 3
Counting using n.m. method: 7 . And counting using ThiefMaster method : 4
很抱歉迟到了 5 年才加入讨论。但我觉得这增加了它。