Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy a recursion happens here?
    primarykey
    data
    text
    <p>Recently I read <a href="https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python">an interesting discussion on how to make a singleton in Python</a>. One of the solutions was a <a href="https://stackoverflow.com/a/6810621/862380">tricky decorator defining a class inside its code as a substitute for decorated class</a>:</p> <pre><code>def singleton(class_): class class_w(class_): _instance = None def __new__(class2, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class2).__new__(class2, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w @singleton class MyClass(object): def __init__(self, text): print text @classmethod def name(class_): print class_.__name__ x = MyClass(111) x.name() y = MyClass(222) print id(x) == id(y) </code></pre> <p>Output is:</p> <pre><code>111 # the __init__ is called only on the 1st time MyClass # the __name__ is preserved True # this is actually the same instance </code></pre> <p>It is stated, that if we use <code>super(MyClass, self).__init__(text)</code> inside <code>__init__</code> of <code>MyClass</code>, we get into <strong>recursion</strong>.</p> <p>I tested and indeed the recursion happens. But, as I understand, <code>MyClass</code> inherits <code>object</code>, so <code>super(MyClass, self)</code> should just merely be <code>object</code>, but it turns out that <code>super(MyClass, self)</code> is <code>__main__.MyClass</code></p> <p>Could you explain what happens here step by step for me to understand the reasons why the recursion happens?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload