deano
deano

Reputation: 67

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. 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. Is it legal to use an 'if' as a condition to init ? Thanks.

Upvotes: 5

Views: 5426

Answers (1)

SteJ
SteJ

Reputation: 1541

Use:

def __new__( cls, *args):

instead of

def __init__( self, *args):

See abort instance creation and especially the accepted answer of new and init

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. 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

Upvotes: 4

Related Questions