简体   繁体   English

Python条件对象实例化

[英]Python conditional object instantiation

I'm taking an online MOOC course, and am having trouble figuring this out, or even how to phrase exactly what it is I'm trying to figure out. 我正在上在线MOOC课程,却很难弄清楚这个问题,甚至无法准确表达我想找出的含义。 The question is asking that an object be created ONLY when a certain string is passed in as an argument. 问题是,仅当某个字符串作为参数传入时才创建对象。 You can see a description of the question here: https://docs.google.com/forms/d/1gt4McfP2ZZkI99JFaHIFcP26lddyTREq4pvDnl4tl0w/viewform?c=0&w=1 The specific part is in the third paragraph. 您可以在此处查看问题的描述: https : //docs.google.com/forms/d/1gt4McfP2ZZkI99JFaHIFcP26lddyTREq4pvDnl4tl0w/viewform?c=0&w= 1特定部分在第三段中。 Is it legal to use an 'if' as a condition to init ? 使用“ if”作为初始化条件是否合法? Thanks. 谢谢。

Use: 采用:

def __new__( cls, *args):

instead of 代替

def __init__( self, *args):

See abort instance creation and especially the accepted answer of new and init 请参阅中止实例创建 ,尤其是可以接受的newinit答案

EDIT: I've added the following code of my own as a simpler example of how it works - You'll need more than this in a real-life scenario: 编辑:我添加了以下代码作为其工作方式的简单示例-在实际场景中,您将需要更多以下代码:

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__ is called before instance creation, and unlike __init__ it returns a value - that value is the instance. __new__ 实例创建之前被调用,并且与__init__不同,它返回一个值-该值实例。 See the second link above for more info - there are code examples there, to borrow one of them: 有关更多信息,请参见上面的第二个链接-那里有代码示例,可以借用其中的一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM