【问题标题】:How do I assign a counter attribute inside a class?如何在类中分配计数器属性?
【发布时间】: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


【解决方案1】:

这是您实际使用的代码:

# 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)

此代码创建已声明类的实例,并让它们单独计算已创建的数量,而无需我们自己进行计数。

【讨论】:

    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2011-11-26
    • 2018-09-05
    • 1970-01-01
    • 2014-08-21
    相关资源
    最近更新 更多