【发布时间】:2021-03-20 21:31:44
【问题描述】:
这是我第一次使用类。我试图了解如何将计数器分配为父类和子类的属性。我不明白如何计算对象的元素。我了解如何计算该特定类的对象/实例数。
这就是我理解使用 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)
这是我在类中定义计数但父形状返回的尝试:
颜色总数:
并且子类返回一个 AttributeError:
AttributeError: 'int' object has no attribute '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)
【问题讨论】:
-
您的代码令人困惑。在这两个 sn-p 中,您都不会创建您声明的类的任何实例。
-
请用您的实际代码更新您的问题。如果我尝试运行您的第二个 sn-p,我不会收到您声称看到的错误。
标签: python class attributes subclass