简体   繁体   中英

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:

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:

  • Using a global keyword as suggested by @nihilok
  • Creating a custom Counter class to handle the integer value (essentially a fancy int).
  • using an int type in the super class and having its methods directly reference it using the super class's name instead of simply using the cls passed in during a class method.

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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM