Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using a <a href="http://en.wikipedia.org/wiki/Factory_method_pattern" rel="nofollow">factory method</a> is the usual way to solve this, <em>especially</em> since instantiating a class is indistinguishable from calling a function in Python.</p> <p>However, if you <em>really</em> want, you can assign to <code>self.__class__</code>:</p> <pre><code>THRESHOLD = 1000 class Small(object): def __init__(self, n): if n &lt; THRESHOLD: self.n = n else: self.__class__ = Big self.__init__(n) class Big(object): def __init__(self, n): if n &lt; THRESHOLD: self.__class__ = Small self.__init__(n) else: self.n = n </code></pre> <p>This works as expected:</p> <pre><code>&gt;&gt;&gt; a = Small(100) &gt;&gt;&gt; type(a) &lt;class 'Small'&gt; &gt;&gt;&gt; b = Small(1234) &gt;&gt;&gt; type(b) &lt;class 'Big'&gt; &gt;&gt;&gt; c = Big(2) &gt;&gt;&gt; type(c) &lt;class 'Small'&gt; </code></pre> <p>If assigning to <code>self.__class__</code> seems too strange, then <a href="http://docs.python.org/reference/datamodel.html#object.__new__" rel="nofollow">you can override <code>__new__</code></a> instead. This method is called before <code>__init__</code> is called and it can be used to pick the class to instantiate:</p> <pre><code>THRESHOLD = 1000 class Switcher(object): def __new__(cls, n): if n &lt; THRESHOLD: new_cls = Small else: new_cls = Big instance = super(Switcher, new_cls).__new__(new_cls, n) if new_cls != cls: instance.__init__(n) return instance class Small(Switcher): def __init__(self, n): self.n = n class Big(Switcher): def __init__(self, n): self.n = n </code></pre>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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