使用python限制类实例的数量 [英] Limit number of class instances with python

查看:254
本文介绍了使用python限制类实例的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ΜyMainclass创建一个简单的 QmainWindows ,如下所示:

  mcManageUiC(QtGui.QMainWindow):
def __init __(self):
super(mcManageUiC,self).__ init __()

self.initUI()

def initUI(self):
self.show()

我的文件我这样启动它:

  def main():
app = QtGui.QApplication argv)
renderManagerVar = mcManageUiC()
sys.exit(app.exec_())


如果__name__ =='__main__':
main ()

我的问题是每次我来源时,它会启动一个新窗口。
我想知道是否有一种方法来检测我的脚本中是否存在以前的类实例(以便我关闭旧的或避免启动一个新的)或任何其他解决方案?



此外,当使用py2exe编译我的代码时,与Windows上的.exe文件同样的问题;它每次都会启动一个新窗口。我可以在setup.py中添加一些东西,不能像这样做吗?



是可能的,如果是,那么如何?



注意:我使用Windows 7 64位编译与eclipse。

解决方案

做这个,你可以使用Class属性来存储所有的实例 - 如果你这样做,你可能想通过weakref模块存储它们作为弱引用,以防止垃圾收集的问题:



class MyClass(object):
_instances = []
def __init __(self):
if(len ._instances)> 2):
self._instances.pop(0).kill()#kill最旧的实例
self._instances.append(self)

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

丑陋。您可能还需要考虑使用某种Factory(有条件地)创建一个新实例。这个方法更简单一些。

  import weakref 
class Factory(object):
def __init__ (self,cls,nallowed):
self.product_class = cls#这个工厂生产的类
self.nallowed = nallowed#允许的实例数量
self.products = []

def __call __(self,* args,** kwargs):
self.products = [x for self.products如果x()不是无] #filter输出死对象
if(len(self.products)< = self.nallowed):
newproduct = self.product_class(* args,** kwargs)
self.products.append(weakref.ref(newproduct) )
return newproduct
else:
return None

#此工厂将创建最多2个MyClass实例
#并拒绝创建更多,直到其中至少有一个
#instances已经死了。
factory = Factory(MyClass,2)
i1 = factory(foo,bar)#instance of MyClass
i2 = factory(bar,baz)#instance of MyClass
i3 = factory(baz,chicken)#None


Μy Mainclass creates a simple QmainWindows like this:

class mcManageUiC(QtGui.QMainWindow):
    def __init__(self):
        super(mcManageUiC, self).__init__()

        self.initUI()

    def initUI(self):
        self.show()

And at the end of my file I launch it like this:

def main():
    app = QtGui.QApplication(sys.argv)
    renderManagerVar = mcManageUiC()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

My problem is that each time i source it, it launches a new window. I would like to know if there is a way to detect existence of previous class instance in my script (so that I close the old one or avoid launching a new one), or any other solutions?

Also, when compiling my code with py2exe, same problem with my .exe file on Windows; it launchs a new window every time. Could i add something in the setup.py for Windows to not act like this?

Is it possible, if yes then how?

Note: I'm using Windows 7 64bit compiling with eclipse.

解决方案

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

这篇关于使用python限制类实例的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆