将类限制为最多一个实例时要抛出哪个Python异常?

2024-09-26 22:10:06 发布

您现在位置:Python中文网/ 问答频道 /正文

应该使用哪些内置的Python异常来表示已经创建了类的实例(例如MCWindow)?接下来是这样的:

window = MCWindow()
try:
    aWindow = MCWindow()
except DontMakeAnotherOneOfTheseInstancesException:
    print("Whoops") # Always the best way to handle exceptions :)

在这里,单例模式可能更合适,但我仍然想知道对于这种情况是否存在内置的异常。你知道吗


Tags: theto实例windowalways内置waybest
3条回答

事实上,只要稍加调整,你就能做到

# python object singleton

class Observer():
    pass
observe = Observer()

class singleton():          
    def __init__(self,):            
        if observe.__dict__.has_key(self.__class__.__name__):
            raise Exception, 'Only one instance of the same "%s" class is allowed' % self.__class__.__name__
        observe.__dict__[self.__class__.__name__]=True
    def some_method(self,):
        # roll your own code
        pass


one = singleton()        
two = singleton()     # will raise an error

observer类是存储状态的地方,singleton类是请求中的类,您只想将其限制为一个实例,您可以创建许多类,如singleton,但只有一个Observer来保持所有类的状态。你知道吗

试试上面的代码,玩得开心。。它对我有用:))


更新创建singleton而不引发异常

class Observer():  

    def __init__(self,):     
        self.error = None

    def __setattr__(self,class_name,instance):
        if not self.__dict__.has_key(instance.__class__.__name__):          
            self.__dict__[class_name]=instance
        else:
            self.error =  'You are only allowed to creat intance once'

    def __getattr__(self,class_name):
        if self.__dict__.has_key(class_name):
            return self.__dict__[class_name]
        else:
            return None

这是要实例化为singleton的类

class test():
    pass

用法

observe = Observer()  

observe.test = test() # This will be created and bound to the variable
observe.test = test() # This will not be created nor bound, but will generate an error msg in observe.error

if not observe.error:
    print 'created successfully'
else:
    print 'Encountered a problem: %s, only this instance has been created: %s' % (observe.error,observe.test)

我不这么认为。 您可能可以使用RuntimeError或您自己继承的异常。 Here您可以找到所有内置异常及其描述的列表。你知道吗

不过,正如您所说,google搜索“python singleton”会给您提供许多更好的解决方案。你知道吗

单例模式在python中并不常见。通常,使用模块代替对象实例。你知道吗

换句话说,没有准确的内在例外。创建自己的,或切换到模块。你知道吗

注意:可以使用一点元编程来创建一个类,该类在实例化时总是返回相同的对象,不涉及异常。

相关问题 更多 >

    热门问题