[英]Shared class int across subclasses
I want to have a counter which increments every time a subclass is instantiated.我想要一个每次实例化子类时递增的计数器。 How would I achieve this such that the last statement below evaluates to True:我将如何实现这一点,以便下面的最后一条语句评估为 True:
class Abstract(ABC):
counter = 0
class A(Abstract):
pass
class B(Abstract):
pass
a = A()
b = B()
a.counter += 1
b.counter == 1
Currently each subclass gets its own counter, rather than sharing the one outlined in the superclass.目前每个子类都有自己的计数器,而不是共享超类中概述的计数器。
Would this work for you?这对你有用吗?
global_counter = 0
class Abstract:
def __init__(self):
global global_counter
global_counter += 1
class A(Abstract):
def __init__(self):
super().__init__()
class B(Abstract):
def __init__(self):
super().__init__()
a = A()
b = B()
print(global_counter) # (output: 2)
So I've implemented several different ways to achieve what I wanted:所以我已经实现了几种不同的方法来实现我想要的:
My favourite (least amount of extra parts and most canonical to how I tend to write my objects) was the last method.我最喜欢的(最少的额外部分并且最符合我编写对象的方式)是最后一种方法。 Where the above translates to something like:上面的内容转化为:
lass Abstract(ABC):
counter = 0
@staticmethod
def increment():
Abstract.counter += 1. # instead of cls.counter += 1
class A(Abstract):
pass
class B(Abstract):
pass
a = A()
b = B()
a.increment()
b.increment()
a.counter == b.counter # now true.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.