Python条件对象实例化

4

1
你能提供描述你的意思的代码吗?你尝试过什么? - DJanssens
1个回答

3

使用:

def __new__( cls, *args):

替代

def __init__( self, *args):

请参考中止Python对象实例创建,特别是__new____init__的被接受答案。

编辑:我添加了自己的一些代码作为更简单的示例 - 在现实情况下,您需要更多的代码:

class MyClass:
    def __new__(cls,**wargs):
        if "create" in wargs: # This is just an example, obviously
            if wargs["create"] >0: # you can use any test here
                # The point here is to "forget" to return the following if your
                # conditions aren't met:
                return super(MyClass,cls).__new__(cls)
        return None
    def __init__(self,**wargs): # Needs to match __new__ in parameter expectations
        print ("New instance!")
a=MyClass()         # a = None and nothing is printed
b=MyClass(create=0) # b = None and nothing is printed
c=MyClass(create=1) # b = <__main__.MyClass object> and prints "New instance!"

__new__在实例创建之前调用,与__init__不同,它会返回一个值,这个值就是这个实例。更多信息请参见上面的第二个链接,那里有一些代码示例可供借鉴:

def SingletonClass(cls):
    class Single(cls):
        __doc__ = cls.__doc__
        _initialized = False
        _instance = None

        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
            return cls._instance

        def __init__(self, *args, **kwargs):
            if self._initialized:
                return
            super(Single, self).__init__(*args, **kwargs)
            self.__class__._initialized = True  # Its crucial to set this variable on the class!
    return Single

谢谢。你的第二部分回答正是我所需要的。 - deano
有没有办法使用__init__函数来实现这个? - pentanol
不,__init__ 用于设置已经创建的实例 - 这就是为什么我们使用 __new__,它允许我们修改对象,随后 __init__ 对其进行操作 - 您可以通过在 __init__ 中引发异常并捕获它来实现类似的效果,但这个答案(至少对我来说)更符合 Python 风格。 - SteJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接