Python条件对象实例化

时间:2015-07-30 03:41:00

标签: python

我参加了一个在线MOOC课程,我很难搞清楚这一点,甚至如何准确地说出我想要弄清楚的是什么。问题是要求只在某个字符串作为参数传入时才创建对象。您可以在此处查看问题的说明:https://docs.google.com/forms/d/1gt4McfP2ZZkI99JFaHIFcP26lddyTREq4pvDnl4tl0w/viewform?c=0&w=1具体部分位于第三段。使用' if'是否合法?作为 init 的条件?感谢。

1 个答案:

答案 0 :(得分:1)

使用:

def __new__( cls, *args):

而不是

def __init__( self, *args):

请参阅abort instance creation,尤其是new and init

的已接受答案

编辑:我已经添加了以下自己的代码,作为其工作原理的简单示例 - 在现实生活中,您需要的不仅仅是:< / p>

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