使用python限制类实例的数量

时间:2012-07-12 18:40:06

标签: python class pyqt instance py2exe

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

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

        self.initUI()

    def initUI(self):
        self.show()

在我的文件末尾,我这样启动它:

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


if __name__ == '__main__':
    main()

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

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

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

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

4 个答案:

答案 0 :(得分:2)

有几种方法可以执行此操作,您可以使用Class属性来存储所有实例 - 如果您这样做,您可能希望通过weakref模块将它们存储为弱引用,以防止垃圾问题收集:

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

虽然这有点难看。您可能还想考虑使用某种类型的Factory(有条件地)创建一个新实例。这种方法更为通用。

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

答案 1 :(得分:1)

您可以通过添加计数器来限制要在代码中创建的实例数:

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)

尝试通过以下方式运行:

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

答案 2 :(得分:0)

你可以垄断一个套接字

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?)"

不知道这是不是一个好方法,但我过去曾使用它,它解决了这个问题

这是为了防止在程序运行时启动程序,而不是从产生多个窗口的单个脚本中启动新窗口...

答案 3 :(得分:0)

使用类变量:

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()
相关问题