Counting instances of a class?

后端 未结 7 1513
失恋的感觉
失恋的感觉 2020-11-29 04:19

I\'ve been cleaning up some code from a module I\'m extending and I can\'t seem to find a way to Pythonify this code:

global_next_id = 1

class Obj:
  def __         


        
7条回答
  •  青春惊慌失措
    2020-11-29 04:42

    class InstanceCounter(object):
      # the instance counter
      counter = 0
    
      def __init__(self, val):
        self.val = all
        # incrementing every time an instance is created
        InstanceCounter.counter += 1
    
      def set_val(self, val):
        self.val = val
    
      def get_val(self, val):
        return self.val
    
      # accessing the instance counter should be done through a class method
    
      @classmethod
      def get_counter(cls):  
        return cls.counter
    
    # See the instance counter as it increments as new instances are created
    a=InstanceCounter(5)
    print(a.get_counter())
    b=InstanceCounter(7)
    print(a.get_counter(), b.get_counter())
    c=InstanceCounter(9)
    print(a.get_counter(), b.get_counter(), c.get_counter())
    

提交回复
热议问题