如何在类中分配计数器属性



这是我第一次使用类。我试图理解如何将计数器分配为父类和子类的属性。我不明白如何计算一个物体的元素。我了解如何计算该特定类的对象/实例数。

这就是我如何理解使用for循环计数/迭代元素

# Parent Class
class Color:
def __init__(self):
self.name = 'Color'

# Inherent Classes
class Green(Color):
def __init__(self):
self.name = 'Green'

class Red(Color):
def __init__(self):
self.name = 'Red'
# Random Generator:
from random import choice
colorL = [choice(['Red', 'Green']) for randomI in range(20)]
cRed = cGreen = 0
for color in colorL:
if color == 'Green':
cGreen=cGreen+1
else:
cRed=cRed+1
# Print statements of random list, max count & specific count of inherent classes   
print(colorL)
print("Total # of colors:", len(colorL))
print("# of Greens:", cGreen)
print("# of Reds:", cRed)

这是我试图在类中定义计数,但父形状返回:

颜色总数:<0x7fd13f4acf08处的列表对象的内置方法计数>

并且子类返回AttributeError:

属性错误:"int"对象没有属性"count">

# Parent Class
class Color:
def __init__(self, name, count):
count = 0
self.name = 'Color'
self.count += 1

# Inherent Classes
class Green(Color):
def __init__(self, name, count):
count = 0
self.name = 'Green'
self.count += 1

class Red(Color):
def __init__(self, name, count):
count = 0
self.name = 'Red'
self.count += 1
# Random Generator:
from random import choice
colorL = [choice(['Red', 'Green']) for randomI in range(20)]
for color in colorL:
if color == 'Green':
GreenC = Green.count
else:
RedC = Red.count
# Print statements of random list, max count & specific count of inherent classes   
print(colorL)
print("Total # of colors:", colorL.count)
print("# of Greens:", GreenC.count)
print("# of Reds:", RedC.count)

这是您实际想要的代码:

# Base Class
class Color:
count = 0
def __init__(self, name):
self.name = name
Color.count += 1
def __repr__(self):
return self.name
# Derived Classes
class Green(Color):
count = 0
def __init__(self):
super().__init__('Green')
Green.count += 1

class Red(Color):
count = 0
def __init__(self):
super().__init__('Red')
Red.count += 1
# Random Generator:
from random import choice
colorL = [choice([Red, Green])() for _ in range(20)]
# Print statements of random list, max count & specific count of derived classes
print(colorL)
print("Total # of colors:", Color.count)
print("# of Greens:", Green.count)
print("# of Reds:", Red.count)

这段代码创建声明类的实例,并使它们单独计数创建的类的数量,而不必自己进行计数。

最新更新