Обратите внимание, что оба ответа выше верны, но они очень разные. Не только в том, как вы их пишете, но и в конечном результате.
Разница возникла бы, если бы вы когда-либо унаследовали класс 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 лет после обсуждения. Но я чувствовал, что это добавило к этому.