Limit number of class instances with python

为君一笑 提交于 2019-12-05 12:40:52

There are a couple ways to do this, you can use a Class attribute to store all the instances -- If you do it this way, you may want to store them as weak references via the weakref module to prevent issues with garbage collecting:

class MyClass(object):
    _instances=[]
    def __init__(self):
        if(len(self._instances) > 2):
            self._instances.pop(0).kill() #kill the oldest instance
        self._instances.append(self)

    def kill(self):
        pass #Do something to kill the instance

This is a little ugly though. You might also want to consider using some sort of Factory which (conditionally) creates a new instance. This method is a little more general.

import weakref
class Factory(object):
     def __init__(self,cls,nallowed):
         self.product_class=cls  #What class this Factory produces
         self.nallowed=nallowed  #Number of instances allowed
         self.products=[]

     def __call__(self,*args,**kwargs):
         self.products=[x for x in self.products if x() is not None] #filter out dead objects
         if(len(self.products) <= self.nallowed):
             newproduct=self.product_class(*args,**kwargs)
             self.products.append(weakref.ref(newproduct))
             return newproduct
         else:
             return None

#This factory will create up to 2 instances of MyClass
#and refuse to create more until at least one of those 
#instances have died.
factory=Factory(MyClass,2)   
i1=factory("foo","bar")      #instance of MyClass
i2=factory("bar","baz")      #instance of MyClass
i3=factory("baz","chicken")  #None

You can limit the number of instances you want to create in your code just by adding a counter:

class A(object):
 ins = 0 # This is a static counter
 def __init__(self):
  if A.ins >= 1: # Check if the number of instances present are more than one. 
   del self
   print "Failed to create another instance" #if > 1, del self and return.
   return
  A.ins += 1
  print "Success",str(self)

Try running via:

lst = []
for i in range(1,101):
 a=A()
 lst.append(a)

you could monopolize a socket

import socket
try:    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
    "Network Error!"

s.settimeout(30)
try:
    s.connect(('localhost' , 123))
except:
    "could not open...already in use socket(program already running?)"

no idea if this is a good method but I have used it in the past and it solves this problem

this was designed to prevent launching a program when it was already running not from launching a new window from within a single script that is spawning several windows...

Use a class variable:

class mcManageUiC(QtGui.QMainWindow):
    singleton = None
    def __init__(self):
        if not mcManageUiC.singleton: #if no instance yet
            super(mcManageUiC, self).__init__()

            self.initUI()
            ...
            mcManageUiC.singleton = self
        else: 
            ...


    def initUI(self):
        self.show()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!