Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, since you didn't give an example, here's the familiar toy minimal class hierarchy:</p> <pre><code>class Base(object): def __init__(self): print("I'm a base") class Child(Base): def __init__(self): super(Child, self).__init__() print("I'm also a child") </code></pre> <p>Now, presumably you want to decide whether to be a <code>Child</code> or not in the middle of, or right after, <code>Base.__init__</code>.</p> <p>The best way to do that is to <em>not</em> do it; just move the choice earlier. Then you don't need to do any re-classing; you just construct the class you actually want, and know it's going to be initialized as appropriate for that class.</p> <p>You can either use a factory function:</p> <pre><code>def basefactory(child=False): if child: return Child() else: return Base() </code></pre> <p>… or an "alternate constructor" method:</p> <pre><code>class Base(object): def __init__(self): print("I'm a base") @classmethod def make(cls, child=False): if child: return Child() else: return cls() </code></pre> <p>Or a custom <code>__new__</code> method:</p> <pre><code>class Base(object): def __init__(self): print("I'm a base") def __new__(cls, child=False): return super(Base, cls).__new__(Child if child else cls) </code></pre> <p>The advantage of all of these mechanisms is that <code>__init__</code> works the way it's supposed to. If someone writes a normal, Pythonic <code>__init__</code> method that correctly calls its superclass, it won't get trapped in an endless loop.</p> <p>The only reason to re-<code>__class__</code> something in the base <code>__init__</code> would be if you wanted to explicitly <em>prevent</em> the child's <code>__init__</code> getting called. That's a very rare case, but if it's what you actually want, it's easy:</p> <pre><code>class Base(object): def __init__(self, child=False): super(Base, self).__init__() if child: self.__class__ = Child </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    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